blob: 227fdc4874c21b9d26d5b051a3edcaa269129c85 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000027#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070030#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070031#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000032#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000033#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "dex_file-inl.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070036#include "dexlayout.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "driver/compiler_driver.h"
38#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010039#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010042#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010043#include "linker/buffered_output_stream.h"
44#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000045#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000046#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/array.h"
48#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010049#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010051#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070052#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070053#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030055#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010056#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010057#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070058#include "verifier/method_verifier.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010059#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000060#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070061
62namespace art {
63
Vladimir Marko9bdf1082016-01-21 12:15:52 +000064namespace { // anonymous namespace
65
66typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
67
68const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
69 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
70}
71
Vladimir Markoe079e212016-05-25 12:49:49 +010072class ChecksumUpdatingOutputStream : public OutputStream {
73 public:
74 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
75 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
76
77 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
78 oat_header_->UpdateChecksum(buffer, byte_count);
79 return out_->WriteFully(buffer, byte_count);
80 }
81
82 off_t Seek(off_t offset, Whence whence) OVERRIDE {
83 return out_->Seek(offset, whence);
84 }
85
86 bool Flush() OVERRIDE {
87 return out_->Flush();
88 }
89
90 private:
91 OutputStream* const out_;
92 OatHeader* const oat_header_;
93};
94
Vladimir Marko0c737df2016-08-01 16:33:16 +010095inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
96 // We want to align the code rather than the preheader.
97 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
98 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
99 return aligned_code_offset - unaligned_code_offset;
100}
101
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000102} // anonymous namespace
103
104// Defines the location of the raw dex file to write.
105class OatWriter::DexFileSource {
106 public:
107 explicit DexFileSource(ZipEntry* zip_entry)
108 : type_(kZipEntry), source_(zip_entry) {
109 DCHECK(source_ != nullptr);
110 }
111
112 explicit DexFileSource(File* raw_file)
113 : type_(kRawFile), source_(raw_file) {
114 DCHECK(source_ != nullptr);
115 }
116
117 explicit DexFileSource(const uint8_t* dex_file)
118 : type_(kRawData), source_(dex_file) {
119 DCHECK(source_ != nullptr);
120 }
121
122 bool IsZipEntry() const { return type_ == kZipEntry; }
123 bool IsRawFile() const { return type_ == kRawFile; }
124 bool IsRawData() const { return type_ == kRawData; }
125
126 ZipEntry* GetZipEntry() const {
127 DCHECK(IsZipEntry());
128 DCHECK(source_ != nullptr);
129 return static_cast<ZipEntry*>(const_cast<void*>(source_));
130 }
131
132 File* GetRawFile() const {
133 DCHECK(IsRawFile());
134 DCHECK(source_ != nullptr);
135 return static_cast<File*>(const_cast<void*>(source_));
136 }
137
138 const uint8_t* GetRawData() const {
139 DCHECK(IsRawData());
140 DCHECK(source_ != nullptr);
141 return static_cast<const uint8_t*>(source_);
142 }
143
144 void Clear() {
145 type_ = kNone;
146 source_ = nullptr;
147 }
148
149 private:
150 enum Type {
151 kNone,
152 kZipEntry,
153 kRawFile,
154 kRawData,
155 };
156
157 Type type_;
158 const void* source_;
159};
160
Vladimir Marko49b0f452015-12-10 13:49:19 +0000161class OatWriter::OatClass {
162 public:
163 OatClass(size_t offset,
164 const dchecked_vector<CompiledMethod*>& compiled_methods,
165 uint32_t num_non_null_compiled_methods,
166 mirror::Class::Status status);
167 OatClass(OatClass&& src) = default;
168 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
169 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
170 size_t SizeOf() const;
171 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
172
173 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
174 return compiled_methods_[class_def_method_index];
175 }
176
177 // Offset of start of OatClass from beginning of OatHeader. It is
178 // used to validate file position when writing.
179 size_t offset_;
180
181 // CompiledMethods for each class_def_method_index, or null if no method is available.
182 dchecked_vector<CompiledMethod*> compiled_methods_;
183
184 // Offset from OatClass::offset_ to the OatMethodOffsets for the
185 // class_def_method_index. If 0, it means the corresponding
186 // CompiledMethod entry in OatClass::compiled_methods_ should be
187 // null and that the OatClass::type_ should be kOatClassBitmap.
188 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
189
190 // Data to write.
191
192 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
193 int16_t status_;
194
195 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
196 uint16_t type_;
197
198 uint32_t method_bitmap_size_;
199
200 // bit vector indexed by ClassDef method index. When
201 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
202 // method has an OatMethodOffsets in methods_offsets_, otherwise
203 // the entry was ommited to save space. If OatClassType::type_ is
204 // not is kOatClassBitmap, the bitmap will be null.
205 std::unique_ptr<BitVector> method_bitmap_;
206
207 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
208 // present in the OatClass. Note that some may be missing if
209 // OatClass::compiled_methods_ contains null values (and
210 // oat_method_offsets_offsets_from_oat_class_ should contain 0
211 // values in this case).
212 dchecked_vector<OatMethodOffsets> method_offsets_;
213 dchecked_vector<OatQuickMethodHeader> method_headers_;
214
215 private:
216 size_t GetMethodOffsetsRawSize() const {
217 return method_offsets_.size() * sizeof(method_offsets_[0]);
218 }
219
220 DISALLOW_COPY_AND_ASSIGN(OatClass);
221};
222
223class OatWriter::OatDexFile {
224 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 OatDexFile(const char* dex_file_location,
226 DexFileSource source,
227 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000228 OatDexFile(OatDexFile&& src) = default;
229
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000230 const char* GetLocation() const {
231 return dex_file_location_data_;
232 }
233
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000234 void ReserveClassOffsets(OatWriter* oat_writer);
235
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000237 bool Write(OatWriter* oat_writer, OutputStream* out) const;
238 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
239
240 // The source of the dex file.
241 DexFileSource source_;
242
243 // Whether to create the type lookup table.
244 CreateTypeLookupTable create_type_lookup_table_;
245
246 // Dex file size. Initialized when writing the dex file.
247 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248
249 // Offset of start of OatDexFile from beginning of OatHeader. It is
250 // used to validate file position when writing.
251 size_t offset_;
252
253 // Data to write.
254 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000256 uint32_t dex_file_location_checksum_;
257 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000258 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000259 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000260
261 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000262 dchecked_vector<uint32_t> class_offsets_;
263
264 private:
265 size_t GetClassOffsetsRawSize() const {
266 return class_offsets_.size() * sizeof(class_offsets_[0]);
267 }
268
269 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
270};
271
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100272#define DCHECK_OFFSET() \
273 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
274 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
275
276#define DCHECK_OFFSET_() \
277 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
278 << "file_offset=" << file_offset << " offset_=" << offset_
279
Jeff Hao608f2ce2016-10-19 11:17:11 -0700280OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000281 : write_state_(WriteState::kAddingDexFileSources),
282 timings_(timings),
283 raw_dex_files_(),
284 zip_archives_(),
285 zipped_dex_files_(),
286 zipped_dex_file_locations_(),
287 compiler_driver_(nullptr),
288 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800289 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000290 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100291 vdex_size_(0u),
292 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100293 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100294 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100295 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000296 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000297 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000298 bss_roots_offset_(0u),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000299 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000300 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100301 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700302 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100303 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000304 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700305 size_dex_file_alignment_(0),
306 size_executable_offset_alignment_(0),
307 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700308 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100310 size_verifier_deps_(0),
311 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100312 size_quickening_info_(0),
313 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700314 size_interpreter_to_interpreter_bridge_(0),
315 size_interpreter_to_compiled_code_bridge_(0),
316 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800317 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700318 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700319 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700320 size_quick_to_interpreter_bridge_(0),
321 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100322 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700323 size_code_(0),
324 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100325 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100326 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700327 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700328 size_oat_dex_file_location_size_(0),
329 size_oat_dex_file_location_data_(0),
330 size_oat_dex_file_location_checksum_(0),
331 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000332 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000333 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000334 size_oat_lookup_table_alignment_(0),
335 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000336 size_oat_class_offsets_alignment_(0),
337 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700338 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700339 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700340 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100341 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000342 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700343 absolute_patch_locations_(),
344 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000345}
346
347bool OatWriter::AddDexFileSource(const char* filename,
348 const char* location,
349 CreateTypeLookupTable create_type_lookup_table) {
350 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
351 uint32_t magic;
352 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700353 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
354 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000355 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
356 return false;
357 } else if (IsDexMagic(magic)) {
358 // The file is open for reading, not writing, so it's OK to let the File destructor
359 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700360 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000361 oat_dex_files_.emplace_back(location,
362 DexFileSource(raw_dex_files_.back().get()),
363 create_type_lookup_table);
364 } else if (IsZipMagic(magic)) {
365 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
366 return false;
367 }
368 } else {
369 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
370 return false;
371 }
372 return true;
373}
374
375// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700376bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000377 const char* location,
378 CreateTypeLookupTable create_type_lookup_table) {
379 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
380 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700381 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000382 ZipArchive* zip_archive = zip_archives_.back().get();
383 if (zip_archive == nullptr) {
384 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
385 << error_msg;
386 return false;
387 }
388 for (size_t i = 0; ; ++i) {
389 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
390 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
391 if (entry == nullptr) {
392 break;
393 }
394 zipped_dex_files_.push_back(std::move(entry));
395 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
396 const char* full_location = zipped_dex_file_locations_.back().c_str();
397 oat_dex_files_.emplace_back(full_location,
398 DexFileSource(zipped_dex_files_.back().get()),
399 create_type_lookup_table);
400 }
401 if (zipped_dex_file_locations_.empty()) {
402 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
403 return false;
404 }
405 return true;
406}
407
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000408// Add dex file source(s) from a vdex file specified by a file handle.
409bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
410 const char* location,
411 CreateTypeLookupTable create_type_lookup_table) {
412 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
413 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000414 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000415 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
416 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000417 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
418 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000419 }
420 if (!DexFile::IsMagicValid(current_dex_data)) {
421 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
422 return false;
423 }
424 // We used `zipped_dex_file_locations_` to keep the strings in memory.
425 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
426 const char* full_location = zipped_dex_file_locations_.back().c_str();
427 oat_dex_files_.emplace_back(full_location,
428 DexFileSource(current_dex_data),
429 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000430 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000431 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000432
433 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
434 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
435 return false;
436 }
437
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000438 if (oat_dex_files_.empty()) {
439 LOG(ERROR) << "No dex files in vdex file created from " << location;
440 return false;
441 }
442 return true;
443}
444
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000445// Add dex file source from raw memory.
446bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
447 const char* location,
448 uint32_t location_checksum,
449 CreateTypeLookupTable create_type_lookup_table) {
450 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
451 if (data.size() < sizeof(DexFile::Header)) {
452 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
453 << data.size() << " File: " << location;
454 return false;
455 }
456 if (!ValidateDexFileHeader(data.data(), location)) {
457 return false;
458 }
459 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
460 if (data.size() < header->file_size_) {
461 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
462 << " file size from header: " << header->file_size_ << " File: " << location;
463 return false;
464 }
465
466 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
467 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
468 return true;
469}
470
471dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
472 dchecked_vector<const char*> locations;
473 locations.reserve(oat_dex_files_.size());
474 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
475 locations.push_back(oat_dex_file.GetLocation());
476 }
477 return locations;
478}
479
480bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100481 File* vdex_file,
482 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000483 InstructionSet instruction_set,
484 const InstructionSetFeatures* instruction_set_features,
485 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800486 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000487 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
489 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
490 CHECK(write_state_ == WriteState::kAddingDexFileSources);
491
David Brazdil7b49e6c2016-09-01 11:06:18 +0100492 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
493 if (!RecordOatDataOffset(oat_rodata)) {
494 return false;
495 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000496
497 std::unique_ptr<MemMap> dex_files_map;
498 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100499
500 // Initialize VDEX and OAT headers.
501 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000502 // Reserve space for Vdex header and checksums.
503 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100504 }
505 size_t oat_data_offset = InitOatHeader(instruction_set,
506 instruction_set_features,
507 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
508 key_value_store);
509 oat_size_ = InitOatDexFiles(oat_data_offset);
510
511 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
512
513 if (kIsVdexEnabled) {
514 std::unique_ptr<BufferedOutputStream> vdex_out(
515 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100516 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000517 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100518 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
519 return false;
520 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100521 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000522 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100523 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000524 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100525 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
526 return false;
527 }
528
529 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
530 // difficult because we're not using the OutputStream directly.
531 if (!oat_dex_files_.empty()) {
532 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
533 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
534 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000535 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000536
David Brazdil7b49e6c2016-09-01 11:06:18 +0100537 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000538 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
539 return false;
540 }
541
David Brazdil7b49e6c2016-09-01 11:06:18 +0100542 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 for (OatDexFile& oat_dex_file : oat_dex_files_) {
544 oat_dex_file.ReserveClassOffsets(this);
545 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100546
David Brazdil7b49e6c2016-09-01 11:06:18 +0100547 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000548 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
549 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000550 }
551
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000552 *opened_dex_files_map = std::move(dex_files_map);
553 *opened_dex_files = std::move(dex_files);
554 write_state_ = WriteState::kPrepareLayout;
555 return true;
556}
557
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100558void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000559 CHECK(write_state_ == WriteState::kPrepareLayout);
560
Vladimir Marko944da602016-02-19 12:27:55 +0000561 relative_patcher_ = relative_patcher;
562 SetMultiOatRelativePatcherAdjustment();
563
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000564 if (compiling_boot_image_) {
565 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800566 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100567 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000568 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100569
David Brazdil7b49e6c2016-09-01 11:06:18 +0100570 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800571 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000572 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800573 offset = InitOatClasses(offset);
574 }
575 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000576 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100577 offset = InitOatMaps(offset);
578 }
579 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000580 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800581 offset = InitOatCode(offset);
582 }
583 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000584 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800585 offset = InitOatCodeDexFiles(offset);
586 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100587 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700588
Vladimir Marko1998cd02017-01-13 13:02:58 +0000589 {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000590 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
591 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100592 }
593
Brian Carlstrome24fa612011-09-29 00:53:55 -0700594 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800595 if (compiling_boot_image_) {
596 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000597 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800598 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000599
600 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700601}
602
Ian Rogers0571d352011-11-03 19:51:38 -0700603OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700604}
605
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100606class OatWriter::DexMethodVisitor {
607 public:
608 DexMethodVisitor(OatWriter* writer, size_t offset)
609 : writer_(writer),
610 offset_(offset),
611 dex_file_(nullptr),
612 class_def_index_(DexFile::kDexNoIndex) {
613 }
614
615 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
616 DCHECK(dex_file_ == nullptr);
617 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
618 dex_file_ = dex_file;
619 class_def_index_ = class_def_index;
620 return true;
621 }
622
623 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
624
625 virtual bool EndClass() {
626 if (kIsDebugBuild) {
627 dex_file_ = nullptr;
628 class_def_index_ = DexFile::kDexNoIndex;
629 }
630 return true;
631 }
632
633 size_t GetOffset() const {
634 return offset_;
635 }
636
637 protected:
638 virtual ~DexMethodVisitor() { }
639
640 OatWriter* const writer_;
641
642 // The offset is usually advanced for each visited method by the derived class.
643 size_t offset_;
644
645 // The dex file and class def index are set in StartClass().
646 const DexFile* dex_file_;
647 size_t class_def_index_;
648};
649
650class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
651 public:
652 OatDexMethodVisitor(OatWriter* writer, size_t offset)
653 : DexMethodVisitor(writer, offset),
654 oat_class_index_(0u),
655 method_offsets_index_(0u) {
656 }
657
658 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
659 DexMethodVisitor::StartClass(dex_file, class_def_index);
660 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
661 method_offsets_index_ = 0u;
662 return true;
663 }
664
665 bool EndClass() {
666 ++oat_class_index_;
667 return DexMethodVisitor::EndClass();
668 }
669
670 protected:
671 size_t oat_class_index_;
672 size_t method_offsets_index_;
673};
674
675class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
676 public:
677 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
678 : DexMethodVisitor(writer, offset),
679 compiled_methods_(),
680 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000681 size_t num_classes = 0u;
682 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
683 num_classes += oat_dex_file.class_offsets_.size();
684 }
685 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100686 compiled_methods_.reserve(256u);
687 }
688
689 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
690 DexMethodVisitor::StartClass(dex_file, class_def_index);
691 compiled_methods_.clear();
692 num_non_null_compiled_methods_ = 0u;
693 return true;
694 }
695
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300696 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
697 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100698 // Fill in the compiled_methods_ array for methods that have a
699 // CompiledMethod. We track the number of non-null entries in
700 // num_non_null_compiled_methods_ since we only want to allocate
701 // OatMethodOffsets for the compiled methods.
702 uint32_t method_idx = it.GetMemberIndex();
703 CompiledMethod* compiled_method =
704 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
705 compiled_methods_.push_back(compiled_method);
706 if (compiled_method != nullptr) {
707 ++num_non_null_compiled_methods_;
708 }
709 return true;
710 }
711
712 bool EndClass() {
713 ClassReference class_ref(dex_file_, class_def_index_);
714 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
715 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700716 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100717 status = compiled_class->GetStatus();
718 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000719 // The oat class status is used only for verification of resolved classes,
720 // so use kStatusErrorResolved whether the class was resolved or unresolved
721 // during compile-time verification.
722 status = mirror::Class::kStatusErrorResolved;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723 } else {
724 status = mirror::Class::kStatusNotReady;
725 }
726
Vladimir Marko49b0f452015-12-10 13:49:19 +0000727 writer_->oat_classes_.emplace_back(offset_,
728 compiled_methods_,
729 num_non_null_compiled_methods_,
730 status);
731 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100732 return DexMethodVisitor::EndClass();
733 }
734
735 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000736 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100737 size_t num_non_null_compiled_methods_;
738};
739
740class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
741 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100742 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100743 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100744 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
745 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100746 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100747 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
748 }
749
750 bool EndClass() {
751 OatDexMethodVisitor::EndClass();
752 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100753 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100754 }
755 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100756 }
757
758 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700759 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000760 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100761 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
762
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100763 if (it.GetMethodCodeItem() != nullptr) {
764 current_quickening_info_offset_ += sizeof(uint32_t);
765 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100766 if (compiled_method != nullptr) {
767 // Derived from CompiledMethod.
768 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100769
Vladimir Marko35831e82015-09-11 11:59:18 +0100770 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
771 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800772 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800773
David Srbecky009e2a62015-04-15 02:46:30 +0100774 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100775 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800776 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000777 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000778 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
779 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800780 // Duplicate methods, we want the same code for both of them so that the oat writer puts
781 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800782 } else {
783 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100784 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800785 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000786 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100787 quick_code_offset = dedupe_map_.GetOrCreate(
788 compiled_method,
789 [this, &deduped, compiled_method, &it, thumb_offset]() {
790 deduped = false;
791 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
792 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800793 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100795 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000796 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100797 // TODO: Should this be a hard failure?
798 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700799 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000800 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
801 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100802 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000803 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100804 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800805 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 // Update quick method header.
808 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
809 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700810 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
812 // to 0-offset and we need to adjust it by code_offset.
813 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100814 if (!compiled_method->GetQuickCode().empty()) {
815 // If the code is compiled, we write the offset of the stack map relative
816 // to the code,
817 if (vmap_table_offset != 0u) {
818 vmap_table_offset += code_offset;
819 DCHECK_LT(vmap_table_offset, code_offset);
820 }
821 } else {
822 if (kIsVdexEnabled) {
823 // We write the offset in the .vdex file.
824 DCHECK_EQ(vmap_table_offset, 0u);
825 vmap_table_offset = current_quickening_info_offset_;
826 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
827 current_quickening_info_offset_ += map.size() * sizeof(map.front());
828 } else {
829 // We write the offset of the quickening info relative to the code.
830 vmap_table_offset += code_offset;
831 DCHECK_LT(vmap_table_offset, code_offset);
832 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800833 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800834 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
835 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
836 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100837 *method_header = OatQuickMethodHeader(vmap_table_offset,
838 frame_size_in_bytes,
839 core_spill_mask,
840 fp_spill_mask,
841 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100842
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000843 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800844 // Update offsets. (Checksum is updated when writing.)
845 offset_ += sizeof(*method_header); // Method header is prepended before code.
846 offset_ += code_size;
847 // Record absolute patch locations.
848 if (!compiled_method->GetPatches().empty()) {
849 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
850 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000851 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100852 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100853 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000854 if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
855 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
856 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
857 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000858 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
859 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
860 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
861 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100862 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100863 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800864 }
Alex Light78382fa2014-06-06 15:45:32 -0700865
David Srbecky91cc06c2016-03-07 16:13:58 +0000866 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000867 // Exclude quickened dex methods (code_size == 0) since they have no native code.
868 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
869 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800870 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000871 debug::MethodDebugInfo info = debug::MethodDebugInfo();
872 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000873 info.dex_file = dex_file_;
874 info.class_def_index = class_def_index_;
875 info.dex_method_index = it.GetMemberIndex();
876 info.access_flags = it.GetMethodAccessFlags();
877 info.code_item = it.GetMethodCodeItem();
878 info.isa = compiled_method->GetInstructionSet();
879 info.deduped = deduped;
880 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
881 info.is_optimized = method_header->IsOptimized();
882 info.is_code_address_text_relative = true;
883 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
884 info.code_size = code_size;
885 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
886 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
887 info.cfi = compiled_method->GetCFIInfo();
888 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100889 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100890
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100891 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
892 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
893 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100894 ++method_offsets_index_;
895 }
896
897 return true;
898 }
899
900 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000901 struct CodeOffsetsKeyComparator {
902 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100903 // Code is deduplicated by CompilerDriver, compare only data pointers.
904 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
905 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000906 }
907 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100908 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
909 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000910 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100911 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
912 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000913 }
914 return false;
915 }
916 };
917
David Srbecky009e2a62015-04-15 02:46:30 +0100918 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
919 const ClassDataItemIterator& it,
920 uint32_t thumb_offset) {
921 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100922 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100923 offset_ += CodeAlignmentSize(offset_, *compiled_method);
924 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100925 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
926 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
927 }
928
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100929 // Deduplication is already done on a pointer basis by the compiler driver,
930 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100931 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100932
David Srbecky009e2a62015-04-15 02:46:30 +0100933 // Cache of compiler's --debuggable option.
934 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100935
936 // Offset in the vdex file for the quickening info.
937 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100938};
939
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100940class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
941 public:
942 InitMapMethodVisitor(OatWriter* writer, size_t offset)
943 : OatDexMethodVisitor(writer, offset) {
944 }
945
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700946 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700947 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000948 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100949 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
950
951 if (compiled_method != nullptr) {
952 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100953 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
954 // be in the vdex file.
955 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700956 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100957
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100958 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
959 uint32_t map_size = map.size() * sizeof(map[0]);
960 if (map_size != 0u) {
961 size_t offset = dedupe_map_.GetOrCreate(
962 map.data(),
963 [this, map_size]() {
964 uint32_t new_offset = offset_;
965 offset_ += map_size;
966 return new_offset;
967 });
968 // Code offset is not initialized yet, so set the map offset to 0u-offset.
969 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700970 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100971 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100972 }
973 ++method_offsets_index_;
974 }
975
976 return true;
977 }
978
979 private:
980 // Deduplication is already done on a pointer basis by the compiler driver,
981 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100982 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100983};
984
985class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
986 public:
987 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800988 : OatDexMethodVisitor(writer, offset),
989 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100990 }
991
992 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700993 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800994 const DexFile::TypeId& type_id =
995 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
996 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
997 // Skip methods that are not in the image.
998 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
999 return true;
1000 }
1001
Vladimir Marko49b0f452015-12-10 13:49:19 +00001002 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001003 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1004
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001005 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001006 if (compiled_method != nullptr) {
1007 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1008 offsets = oat_class->method_offsets_[method_offsets_index_];
1009 ++method_offsets_index_;
1010 }
1011
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001012 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001013 // Unchecked as we hold mutator_lock_ on entry.
1014 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001015 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001016 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
1017 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001018 ArtMethod* method;
1019 if (writer_->HasBootImage()) {
1020 const InvokeType invoke_type = it.GetMethodInvokeType(
1021 dex_file_->GetClassDef(class_def_index_));
1022 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1023 *dex_file_,
1024 it.GetMemberIndex(),
1025 dex_cache,
1026 ScopedNullHandle<mirror::ClassLoader>(),
1027 nullptr,
1028 invoke_type);
1029 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001030 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001031 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001032 soa.Self()->AssertPendingException();
1033 mirror::Throwable* exc = soa.Self()->GetException();
1034 std::string dump = exc->Dump();
1035 LOG(FATAL) << dump;
1036 UNREACHABLE();
1037 }
1038 } else {
1039 // Should already have been resolved by the compiler, just peek into the dex cache.
1040 // It may not be resolved if the class failed to verify, in this case, don't set the
1041 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1042 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001043 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001044 if (method != nullptr &&
1045 compiled_method != nullptr &&
1046 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001047 method->SetEntryPointFromQuickCompiledCodePtrSize(
1048 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1049 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001050
1051 return true;
1052 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001053
1054 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001055 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001056};
1057
1058class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1059 public:
1060 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001061 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001062 : OatDexMethodVisitor(writer, relative_offset),
Vladimir Markoec786222016-12-20 16:24:13 +00001063 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001064 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001065 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001066 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001067 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001068 class_linker_(Runtime::Current()->GetClassLinker()),
1069 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001070 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001071 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001072 // If we're creating the image, the address space must be ready so that we can apply patches.
1073 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001074 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001075 }
1076
Vladimir Markof4da6752014-08-01 19:04:18 +01001077 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001078 }
1079
1080 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001081 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001082 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1083 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001084 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001085 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001086 }
1087 return true;
1088 }
1089
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001090 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001091 bool result = OatDexMethodVisitor::EndClass();
1092 if (oat_class_index_ == writer_->oat_classes_.size()) {
1093 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001094 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001095 if (UNLIKELY(offset_ == 0u)) {
1096 PLOG(ERROR) << "Failed to write final relative call thunks";
1097 result = false;
1098 }
1099 }
1100 return result;
1101 }
1102
1103 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001104 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001105 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001106 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1107
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001108 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001109 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001110 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001111 size_t file_offset = file_offset_;
1112 OutputStream* out = out_;
1113
Vladimir Marko35831e82015-09-11 11:59:18 +01001114 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1115 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001116
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001117 // Deduplicate code arrays.
1118 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1119 if (method_offsets.code_offset_ > offset_) {
1120 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1121 if (offset_ == 0u) {
1122 ReportWriteFailure("relative call thunk", it);
1123 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001124 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001125 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1126 if (alignment_size != 0) {
1127 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001128 ReportWriteFailure("code alignment padding", it);
1129 return false;
1130 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001131 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001132 DCHECK_OFFSET_();
1133 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001134 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001135 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1136 DCHECK_EQ(method_offsets.code_offset_,
1137 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001138 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001139 const OatQuickMethodHeader& method_header =
1140 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001141 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001142 ReportWriteFailure("method header", it);
1143 return false;
1144 }
1145 writer_->size_method_header_ += sizeof(method_header);
1146 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001147 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001148
1149 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001150 patched_code_.assign(quick_code.begin(), quick_code.end());
1151 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001152 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001153 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001154 switch (patch.GetType()) {
1155 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001156 // NOTE: Relative calls across oat files are not supported.
1157 uint32_t target_offset = GetTargetOffset(patch);
1158 writer_->relative_patcher_->PatchCall(&patched_code_,
1159 literal_offset,
1160 offset_ + literal_offset,
1161 target_offset);
1162 break;
1163 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001164 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001165 uint32_t target_offset = GetDexCacheOffset(patch);
1166 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1167 patch,
1168 offset_ + literal_offset,
1169 target_offset);
1170 break;
1171 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001172 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001173 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1174 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1175 patch,
1176 offset_ + literal_offset,
1177 target_offset);
1178 break;
1179 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001180 case LinkerPatch::Type::kStringBssEntry: {
1181 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1182 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1183 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1184 patch,
1185 offset_ + literal_offset,
1186 target_offset);
1187 break;
1188 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001189 case LinkerPatch::Type::kTypeRelative: {
1190 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1191 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1192 patch,
1193 offset_ + literal_offset,
1194 target_offset);
1195 break;
1196 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001197 case LinkerPatch::Type::kTypeBssEntry: {
1198 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1199 uint32_t target_offset = writer_->bss_type_entries_.Get(ref);
1200 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1201 patch,
1202 offset_ + literal_offset,
1203 target_offset);
1204 break;
1205 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001206 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001207 uint32_t target_offset = GetTargetOffset(patch);
1208 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1209 break;
1210 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001211 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001212 ArtMethod* method = GetTargetMethod(patch);
1213 PatchMethodAddress(&patched_code_, literal_offset, method);
1214 break;
1215 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001216 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001217 mirror::String* string = GetTargetString(patch);
1218 PatchObjectAddress(&patched_code_, literal_offset, string);
1219 break;
1220 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001221 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001222 mirror::Class* type = GetTargetType(patch);
1223 PatchObjectAddress(&patched_code_, literal_offset, type);
1224 break;
1225 }
1226 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001227 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001228 break;
1229 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001230 }
1231 }
1232 }
1233
Vladimir Markoe079e212016-05-25 12:49:49 +01001234 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001235 ReportWriteFailure("method code", it);
1236 return false;
1237 }
1238 writer_->size_code_ += code_size;
1239 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001240 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001241 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001242 ++method_offsets_index_;
1243 }
1244
1245 return true;
1246 }
1247
1248 private:
Vladimir Markoec786222016-12-20 16:24:13 +00001249 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001250 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001251 const size_t file_offset_;
1252 const ScopedObjectAccess soa_;
1253 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001254 ClassLinker* const class_linker_;
Vladimir Markoec786222016-12-20 16:24:13 +00001255 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001256 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001257
1258 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1259 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001260 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001261 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001262
Mathieu Chartiere401d142015-04-22 13:56:20 -07001263 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001264 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001265 MethodReference ref = patch.TargetMethod();
Vladimir Markoec786222016-12-20 16:24:13 +00001266 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001267 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1268 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001269 ArtMethod* method = dex_cache->GetResolvedMethod(
1270 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001271 CHECK(method != nullptr);
1272 return method;
1273 }
1274
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001275 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001276 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1277 // If there's no new compiled code, either we're compiling an app and the target method
1278 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001279 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001280 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001281 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001282 PointerSize size =
1283 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001284 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1285 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001286 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001287 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1288 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1289 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1290 target_offset = PointerToLowMemUInt32(oat_code_offset);
1291 } else {
1292 target_offset = target->IsNative()
1293 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1294 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1295 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001296 }
1297 return target_offset;
1298 }
1299
Vladimir Markoec786222016-12-20 16:24:13 +00001300 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001301 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001302 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001303 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001304 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1305 }
1306
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001307 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoec786222016-12-20 16:24:13 +00001308 DCHECK(writer_->HasImage());
1309 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
1310 ObjPtr<mirror::Class> type =
1311 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001312 CHECK(type != nullptr);
Vladimir Markoec786222016-12-20 16:24:13 +00001313 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001314 }
1315
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001316 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001317 ScopedObjectAccessUnchecked soa(Thread::Current());
1318 StackHandleScope<1> hs(soa.Self());
1319 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1320 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1321 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1322 patch.TargetStringIndex(),
1323 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001324 DCHECK(string != nullptr);
1325 DCHECK(writer_->HasBootImage() ||
1326 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1327 return string;
1328 }
1329
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001330 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001331 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001332 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1333 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1334 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1335 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001336 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001337 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001338 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1339 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001340 }
1341 }
1342
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001343 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001344 DCHECK(writer_->HasBootImage());
1345 object = writer_->image_writer_->GetImageAddress(object);
1346 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1347 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1348 // TODO: Clean up offset types. The target offset must be treated as signed.
1349 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1350 }
1351
Vladimir Markof4da6752014-08-01 19:04:18 +01001352 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001353 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001354 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001355 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001356 } else {
1357 // NOTE: We're using linker patches for app->boot references when the image can
1358 // be relocated and therefore we need to emit .oat_patches. We're not using this
1359 // for app->app references, so check that the object is in the image space.
1360 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001361 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001362 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001363 uint32_t address = PointerToLowMemUInt32(object);
1364 DCHECK_LE(offset + 4, code->size());
1365 uint8_t* data = &(*code)[offset];
1366 data[0] = address & 0xffu;
1367 data[1] = (address >> 8) & 0xffu;
1368 data[2] = (address >> 16) & 0xffu;
1369 data[3] = (address >> 24) & 0xffu;
1370 }
1371
Mathieu Chartiere401d142015-04-22 13:56:20 -07001372 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001373 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001374 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001375 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001376 } else if (kIsDebugBuild) {
1377 // NOTE: We're using linker patches for app->boot references when the image can
1378 // be relocated and therefore we need to emit .oat_patches. We're not using this
1379 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001380 std::vector<gc::space::ImageSpace*> image_spaces =
1381 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1382 bool contains_method = false;
1383 for (gc::space::ImageSpace* image_space : image_spaces) {
1384 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1385 contains_method |=
1386 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1387 }
1388 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001389 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001390 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001391 uint32_t address = PointerToLowMemUInt32(method);
1392 DCHECK_LE(offset + 4, code->size());
1393 uint8_t* data = &(*code)[offset];
1394 data[0] = address & 0xffu;
1395 data[1] = (address >> 8) & 0xffu;
1396 data[2] = (address >> 16) & 0xffu;
1397 data[3] = (address >> 24) & 0xffu;
1398 }
1399
Vladimir Markof4da6752014-08-01 19:04:18 +01001400 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001401 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001402 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001403 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001404 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1405 // TODO: Clean up offset types.
1406 // The target_offset must be treated as signed for cross-oat patching.
1407 const void* target = reinterpret_cast<const void*>(
1408 writer_->image_writer_->GetOatDataBegin(oat_index) +
1409 static_cast<int32_t>(target_offset));
1410 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001411 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001412 DCHECK_LE(offset + 4, code->size());
1413 uint8_t* data = &(*code)[offset];
1414 data[0] = address & 0xffu;
1415 data[1] = (address >> 8) & 0xffu;
1416 data[2] = (address >> 16) & 0xffu;
1417 data[3] = (address >> 24) & 0xffu;
1418 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001419};
1420
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001421class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1422 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001423 WriteMapMethodVisitor(OatWriter* writer,
1424 OutputStream* out,
1425 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001426 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001427 : OatDexMethodVisitor(writer, relative_offset),
1428 out_(out),
1429 file_offset_(file_offset) {
1430 }
1431
1432 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001433 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1435
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001436 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001437 size_t file_offset = file_offset_;
1438 OutputStream* out = out_;
1439
Mingyao Yang063fc772016-08-02 11:02:54 -07001440 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001441 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001442 ++method_offsets_index_;
1443
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001444 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1445 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1446 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001447 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001448
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001449 // If vdex is enabled, only emit the map for compiled code. The quickening info
1450 // is emitted in the vdex already.
1451 if (map_offset != 0u &&
1452 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001453 // Transform map_offset to actual oat data offset.
1454 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1455 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001456 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001457
1458 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1459 size_t map_size = map.size() * sizeof(map[0]);
1460 if (map_offset == offset_) {
1461 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001462 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001463 ReportWriteFailure(it);
1464 return false;
1465 }
1466 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001467 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 }
1469 DCHECK_OFFSET_();
1470 }
1471
1472 return true;
1473 }
1474
1475 private:
1476 OutputStream* const out_;
1477 size_t const file_offset_;
1478
1479 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001480 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001481 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001482 }
1483};
1484
1485// Visit all methods from all classes in all dex files with the specified visitor.
1486bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1487 for (const DexFile* dex_file : *dex_files_) {
1488 const size_t class_def_count = dex_file->NumClassDefs();
1489 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1490 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1491 return false;
1492 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001493 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1494 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1495 const uint8_t* class_data = dex_file->GetClassData(class_def);
1496 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1497 ClassDataItemIterator it(*dex_file, class_data);
1498 while (it.HasNextStaticField()) {
1499 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001500 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001501 while (it.HasNextInstanceField()) {
1502 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001503 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001504 size_t class_def_method_index = 0u;
1505 while (it.HasNextDirectMethod()) {
1506 if (!visitor->VisitMethod(class_def_method_index, it)) {
1507 return false;
1508 }
1509 ++class_def_method_index;
1510 it.Next();
1511 }
1512 while (it.HasNextVirtualMethod()) {
1513 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1514 return false;
1515 }
1516 ++class_def_method_index;
1517 it.Next();
1518 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001519 }
1520 }
1521 if (UNLIKELY(!visitor->EndClass())) {
1522 return false;
1523 }
1524 }
1525 }
1526 return true;
1527}
1528
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001529size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1530 const InstructionSetFeatures* instruction_set_features,
1531 uint32_t num_dex_files,
1532 SafeMap<std::string, std::string>* key_value_store) {
1533 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1534 oat_header_.reset(OatHeader::Create(instruction_set,
1535 instruction_set_features,
1536 num_dex_files,
1537 key_value_store));
1538 size_oat_header_ += sizeof(OatHeader);
1539 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001540 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001541}
1542
1543size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001544 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1545 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001546 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001547 oat_dex_file.offset_ = offset;
1548 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001549 }
1550 return offset;
1551}
1552
Brian Carlstrom389efb02012-01-11 12:06:26 -08001553size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001554 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001555 InitOatClassesMethodVisitor visitor(this, offset);
1556 bool success = VisitDexMethods(&visitor);
1557 CHECK(success);
1558 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001559
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001560 // Update oat_dex_files_.
1561 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001562 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1563 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001564 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001565 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001566 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001567 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001568 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001569 CHECK(oat_class_it == oat_classes_.end());
1570
1571 return offset;
1572}
1573
1574size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001575 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1576 return offset;
1577 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001578 InitMapMethodVisitor visitor(this, offset);
1579 bool success = VisitDexMethods(&visitor);
1580 DCHECK(success);
1581 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001582
Brian Carlstrome24fa612011-09-29 00:53:55 -07001583 return offset;
1584}
1585
1586size_t OatWriter::InitOatCode(size_t offset) {
1587 // calculate the offsets within OatHeader to executable code
1588 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001589 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001590 // required to be on a new page boundary
1591 offset = RoundUp(offset, kPageSize);
1592 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001593 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001594 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001595 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001596
Ian Rogers848871b2013-08-05 10:56:33 -07001597 #define DO_TRAMPOLINE(field, fn_name) \
1598 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001599 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1600 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001601 (field) = compiler_driver_->Create ## fn_name(); \
1602 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001603
Ian Rogers848871b2013-08-05 10:56:33 -07001604 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001605 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001606 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001607 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1608 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001609
Ian Rogers848871b2013-08-05 10:56:33 -07001610 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001611 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001612 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1613 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1614 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001615 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001616 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001617 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001618 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001619 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001620 return offset;
1621}
1622
1623size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001624 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1625 return offset;
1626 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001627 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1628 bool success = VisitDexMethods(&code_visitor);
1629 DCHECK(success);
1630 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001631
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001632 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001633 InitImageMethodVisitor image_visitor(this, offset);
1634 success = VisitDexMethods(&image_visitor);
1635 DCHECK(success);
1636 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001637 }
Logan Chien8b977d32012-02-21 19:14:55 +08001638
Brian Carlstrome24fa612011-09-29 00:53:55 -07001639 return offset;
1640}
1641
Vladimir Markoaad75c62016-10-03 08:46:48 +00001642void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001643 if (HasBootImage()) {
1644 DCHECK(bss_string_entries_.empty());
1645 if (bss_type_entries_.empty()) {
1646 // Nothing to put to the .bss section.
1647 return;
1648 }
1649 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001650
1651 // Allocate space for app dex cache arrays in the .bss section.
1652 bss_start_ = RoundUp(oat_size_, kPageSize);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001653 bss_size_ = 0u;
Vladimir Marko1998cd02017-01-13 13:02:58 +00001654 if (!HasBootImage()) {
1655 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1656 for (const DexFile* dex_file : *dex_files_) {
1657 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1658 DexCacheArraysLayout layout(pointer_size, dex_file);
1659 bss_size_ += layout.Size();
1660 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001661 }
1662
1663 bss_roots_offset_ = bss_size_;
1664
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001665 // Prepare offsets for .bss Class entries.
1666 for (auto& entry : bss_type_entries_) {
1667 DCHECK_EQ(entry.second, 0u);
1668 entry.second = bss_start_ + bss_size_;
1669 bss_size_ += sizeof(GcRoot<mirror::Class>);
1670 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001671 // Prepare offsets for .bss String entries.
1672 for (auto& entry : bss_string_entries_) {
1673 DCHECK_EQ(entry.second, 0u);
1674 entry.second = bss_start_ + bss_size_;
1675 bss_size_ += sizeof(GcRoot<mirror::String>);
1676 }
1677}
1678
David Srbeckybc90fd02015-04-22 19:40:27 +01001679bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001680 CHECK(write_state_ == WriteState::kWriteRoData);
1681
Vladimir Markoe079e212016-05-25 12:49:49 +01001682 // Wrap out to update checksum with each write.
1683 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1684 out = &checksum_updating_out;
1685
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001686 if (!WriteClassOffsets(out)) {
1687 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001688 return false;
1689 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001690
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001691 if (!WriteClasses(out)) {
1692 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001693 return false;
1694 }
1695
Vladimir Markof4da6752014-08-01 19:04:18 +01001696 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001697 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001698 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001699 return false;
1700 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001701 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001702 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001703 relative_offset = WriteMaps(out, file_offset, relative_offset);
1704 if (relative_offset == 0) {
1705 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1706 return false;
1707 }
1708
David Srbeckybc90fd02015-04-22 19:40:27 +01001709 // Write padding.
1710 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1711 relative_offset += size_executable_offset_alignment_;
1712 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1713 size_t expected_file_offset = file_offset + relative_offset;
1714 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1715 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1716 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1717 return 0;
1718 }
1719 DCHECK_OFFSET();
1720
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001721 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001722 return true;
1723}
1724
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001725class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1726 public:
1727 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1728 : DexMethodVisitor(writer, offset),
1729 out_(out),
1730 written_bytes_(0u) {}
1731
1732 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1733 const ClassDataItemIterator& it) {
1734 if (it.GetMethodCodeItem() == nullptr) {
1735 // No CodeItem. Native or abstract method.
1736 return true;
1737 }
1738
1739 uint32_t method_idx = it.GetMemberIndex();
1740 CompiledMethod* compiled_method =
1741 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1742
1743 uint32_t length = 0;
1744 const uint8_t* data = nullptr;
1745 // VMap only contains quickening info if this method is not compiled.
1746 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1747 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1748 data = map.data();
1749 length = map.size() * sizeof(map.front());
1750 }
1751
1752 if (!out_->WriteFully(&length, sizeof(length)) ||
1753 !out_->WriteFully(data, length)) {
1754 PLOG(ERROR) << "Failed to write quickening info for "
1755 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1756 return false;
1757 }
1758 offset_ += sizeof(length) + length;
1759 written_bytes_ += sizeof(length) + length;
1760 return true;
1761 }
1762
1763 size_t GetNumberOfWrittenBytes() const {
1764 return written_bytes_;
1765 }
1766
1767 private:
1768 OutputStream* const out_;
1769 size_t written_bytes_;
1770};
1771
1772bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1773 if (!kIsVdexEnabled) {
1774 return true;
1775 }
1776
1777 size_t initial_offset = vdex_size_;
1778 size_t start_offset = RoundUp(initial_offset, 4u);
1779
1780 vdex_size_ = start_offset;
1781 vdex_quickening_info_offset_ = vdex_size_;
1782 size_quickening_info_alignment_ = start_offset - initial_offset;
1783
1784 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1785 if (actual_offset != static_cast<off_t>(start_offset)) {
1786 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1787 << " Expected: " << start_offset
1788 << " Output: " << vdex_out->GetLocation();
1789 return false;
1790 }
1791
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001792 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1793 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1794 if (!VisitDexMethods(&visitor)) {
1795 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1796 return false;
1797 }
1798
1799 if (!vdex_out->Flush()) {
1800 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1801 << " File: " << vdex_out->GetLocation();
1802 return false;
1803 }
1804 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1805 } else {
1806 // We know we did not quicken.
1807 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001808 }
1809
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001810 vdex_size_ += size_quickening_info_;
1811 return true;
1812}
1813
David Brazdil5d5a36b2016-09-14 15:34:10 +01001814bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1815 if (!kIsVdexEnabled) {
1816 return true;
1817 }
1818
1819 if (verifier_deps == nullptr) {
1820 // Nothing to write. Record the offset, but no need
1821 // for alignment.
1822 vdex_verifier_deps_offset_ = vdex_size_;
1823 return true;
1824 }
1825
1826 size_t initial_offset = vdex_size_;
1827 size_t start_offset = RoundUp(initial_offset, 4u);
1828
1829 vdex_size_ = start_offset;
1830 vdex_verifier_deps_offset_ = vdex_size_;
1831 size_verifier_deps_alignment_ = start_offset - initial_offset;
1832
1833 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1834 if (actual_offset != static_cast<off_t>(start_offset)) {
1835 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1836 << " Expected: " << start_offset
1837 << " Output: " << vdex_out->GetLocation();
1838 return false;
1839 }
1840
1841 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001842 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001843
1844 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1845 PLOG(ERROR) << "Failed to write verifier deps."
1846 << " File: " << vdex_out->GetLocation();
1847 return false;
1848 }
1849 if (!vdex_out->Flush()) {
1850 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1851 << " File: " << vdex_out->GetLocation();
1852 return false;
1853 }
1854
1855 size_verifier_deps_ = buffer.size();
1856 vdex_size_ += size_verifier_deps_;
1857 return true;
1858}
1859
David Srbeckybc90fd02015-04-22 19:40:27 +01001860bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001861 CHECK(write_state_ == WriteState::kWriteText);
1862
Vladimir Markoe079e212016-05-25 12:49:49 +01001863 // Wrap out to update checksum with each write.
1864 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1865 out = &checksum_updating_out;
1866
Vladimir Marko944da602016-02-19 12:27:55 +00001867 SetMultiOatRelativePatcherAdjustment();
1868
David Srbeckybc90fd02015-04-22 19:40:27 +01001869 const size_t file_offset = oat_data_offset_;
1870 size_t relative_offset = oat_header_->GetExecutableOffset();
1871 DCHECK_OFFSET();
1872
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001873 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001874 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001875 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001876 return false;
1877 }
1878
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001879 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1880 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001881 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001882 return false;
1883 }
1884
Vladimir Markof4da6752014-08-01 19:04:18 +01001885 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001886 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001887 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1888 return false;
1889 }
1890
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001891 if (kIsDebugBuild) {
1892 uint32_t size_total = 0;
1893 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001894 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1895 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001896
David Brazdil7b49e6c2016-09-01 11:06:18 +01001897 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001898 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001899 DO_STAT(size_dex_file_alignment_);
1900 DO_STAT(size_executable_offset_alignment_);
1901 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001902 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001903 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001904 DO_STAT(size_verifier_deps_);
1905 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001906 DO_STAT(size_quickening_info_);
1907 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001908 DO_STAT(size_interpreter_to_interpreter_bridge_);
1909 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1910 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001911 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001912 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001913 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001914 DO_STAT(size_quick_to_interpreter_bridge_);
1915 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001916 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001917 DO_STAT(size_code_);
1918 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001919 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001920 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001921 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001922 DO_STAT(size_oat_dex_file_location_size_);
1923 DO_STAT(size_oat_dex_file_location_data_);
1924 DO_STAT(size_oat_dex_file_location_checksum_);
1925 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001926 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001927 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001928 DO_STAT(size_oat_lookup_table_alignment_);
1929 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001930 DO_STAT(size_oat_class_offsets_alignment_);
1931 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001932 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001933 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001934 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001935 DO_STAT(size_oat_class_method_offsets_);
1936 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001937
David Brazdil7b49e6c2016-09-01 11:06:18 +01001938 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1939
1940 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1941 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001942 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001943
David Brazdil7b49e6c2016-09-01 11:06:18 +01001944 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1945 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001946
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001947 write_state_ = WriteState::kWriteHeader;
1948 return true;
1949}
1950
1951bool OatWriter::WriteHeader(OutputStream* out,
1952 uint32_t image_file_location_oat_checksum,
1953 uintptr_t image_file_location_oat_begin,
1954 int32_t image_patch_delta) {
1955 CHECK(write_state_ == WriteState::kWriteHeader);
1956
1957 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1958 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001959 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001960 CHECK_EQ(image_patch_delta, 0);
1961 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1962 } else {
1963 CHECK_ALIGNED(image_patch_delta, kPageSize);
1964 oat_header_->SetImagePatchDelta(image_patch_delta);
1965 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001966 oat_header_->UpdateChecksumWithHeaderData();
1967
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001968 const size_t file_offset = oat_data_offset_;
1969
1970 off_t current_offset = out->Seek(0, kSeekCurrent);
1971 if (current_offset == static_cast<off_t>(-1)) {
1972 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1973 return false;
1974 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001975 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001976 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1977 return false;
1978 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001979 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001980
1981 // Flush all other data before writing the header.
1982 if (!out->Flush()) {
1983 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1984 return false;
1985 }
1986 // Write the header.
1987 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001988 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001989 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1990 return false;
1991 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001992 // Flush the header data.
1993 if (!out->Flush()) {
1994 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001995 return false;
1996 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001997
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001998 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1999 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2000 return false;
2001 }
2002 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2003
2004 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002005 return true;
2006}
2007
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002008bool OatWriter::WriteClassOffsets(OutputStream* out) {
2009 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2010 if (oat_dex_file.class_offsets_offset_ != 0u) {
2011 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
2012 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
2013 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2014 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
2015 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00002016 return false;
2017 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002018 if (!oat_dex_file.WriteClassOffsets(this, out)) {
2019 return false;
2020 }
2021 }
2022 }
2023 return true;
2024}
2025
2026bool OatWriter::WriteClasses(OutputStream* out) {
2027 for (OatClass& oat_class : oat_classes_) {
2028 if (!oat_class.Write(this, out, oat_data_offset_)) {
2029 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
2030 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00002031 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002032 }
2033 return true;
2034}
2035
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002036size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002037 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002038 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2039 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2040 return 0;
2041 }
2042 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002043 size_vmap_table_ = relative_offset - vmap_tables_offset;
2044
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002045 return relative_offset;
2046}
2047
2048size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002049 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002050 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002051
Ian Rogers848871b2013-08-05 10:56:33 -07002052 #define DO_TRAMPOLINE(field) \
2053 do { \
2054 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2055 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002056 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002057 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002058 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002059 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002060 return false; \
2061 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002062 size_ ## field += (field)->size(); \
2063 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002064 DCHECK_OFFSET(); \
2065 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002066
Ian Rogers848871b2013-08-05 10:56:33 -07002067 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002068 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002069 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002070 DO_TRAMPOLINE(quick_resolution_trampoline_);
2071 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2072 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002073 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002074 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002075}
2076
Ian Rogers3d504072014-03-01 09:16:49 -08002077size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002078 const size_t file_offset,
2079 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002080 #define VISIT(VisitorType) \
2081 do { \
2082 VisitorType visitor(this, out, file_offset, relative_offset); \
2083 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2084 return 0; \
2085 } \
2086 relative_offset = visitor.GetOffset(); \
2087 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002088
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002089 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002090
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002091 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002092
Vladimir Markob163bb72015-03-31 21:49:49 +01002093 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2094 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2095 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2096
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002097 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002098}
2099
Vladimir Marko944da602016-02-19 12:27:55 +00002100bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002101 // Get the elf file offset of the oat file.
2102 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2103 if (raw_file_offset == static_cast<off_t>(-1)) {
2104 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2105 return false;
2106 }
2107 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2108 return true;
2109}
2110
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002111bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2112 // Read the dex file header and perform minimal verification.
2113 uint8_t raw_header[sizeof(DexFile::Header)];
2114 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2115 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2116 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2117 return false;
2118 }
2119 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2120 return false;
2121 }
2122
2123 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2124 oat_dex_file->dex_file_size_ = header->file_size_;
2125 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2126 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2127 return true;
2128}
2129
2130bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2131 if (!DexFile::IsMagicValid(raw_header)) {
2132 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2133 return false;
2134 }
2135 if (!DexFile::IsVersionValid(raw_header)) {
2136 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2137 return false;
2138 }
2139 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2140 if (header->file_size_ < sizeof(DexFile::Header)) {
2141 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2142 << " File: " << location;
2143 return false;
2144 }
2145 return true;
2146}
2147
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002148bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002149 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002150
David Brazdil7b49e6c2016-09-01 11:06:18 +01002151 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002152
2153 // Write dex files.
2154 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002155 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002156 return false;
2157 }
2158 }
2159
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002160 CloseSources();
2161 return true;
2162}
2163
2164void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002165 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2166 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2167 }
2168 zipped_dex_files_.clear();
2169 zip_archives_.clear();
2170 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002171}
2172
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002173bool OatWriter::WriteDexFile(OutputStream* out,
2174 File* file,
2175 OatDexFile* oat_dex_file,
2176 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002177 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002178 return false;
2179 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002180 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002181 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002182 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2183 return false;
2184 }
2185 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002186 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002187 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002188 return false;
2189 }
2190 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002191 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002192 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002193 return false;
2194 }
2195 } else {
2196 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002197 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002198 return false;
2199 }
2200 }
2201
2202 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002203 if (kIsVdexEnabled) {
2204 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2205 vdex_size_ += oat_dex_file->dex_file_size_;
2206 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002207 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002208 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2209 oat_size_ += oat_dex_file->dex_file_size_;
2210 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002211 size_dex_file_ += oat_dex_file->dex_file_size_;
2212 return true;
2213}
2214
2215bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2216 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002217 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2218 size_t start_offset = RoundUp(initial_offset, 4);
2219 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2220 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002221
2222 // Seek to the start of the dex file and flush any pending operations in the stream.
2223 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002224 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2225 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002226 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002227 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002228 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2229 return false;
2230 }
2231 if (!out->Flush()) {
2232 PLOG(ERROR) << "Failed to flush before writing dex file."
2233 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2234 return false;
2235 }
2236 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002237 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002238 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002239 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002240 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2241 return false;
2242 }
2243
David Brazdil7b49e6c2016-09-01 11:06:18 +01002244 if (kIsVdexEnabled) {
2245 vdex_size_ = start_offset;
2246 } else {
2247 oat_size_ = start_offset;
2248 }
2249 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002250 return true;
2251}
2252
Jeff Hao608f2ce2016-10-19 11:17:11 -07002253bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2254 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2255 std::string error_msg;
2256 std::string location(oat_dex_file->GetLocation());
2257 std::unique_ptr<const DexFile> dex_file;
2258 if (oat_dex_file->source_.IsZipEntry()) {
2259 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2260 std::unique_ptr<MemMap> mem_map(
2261 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2262 dex_file = DexFile::Open(location,
2263 zip_entry->GetCrc32(),
2264 std::move(mem_map),
2265 /* verify */ true,
2266 /* verify_checksum */ true,
2267 &error_msg);
2268 } else {
2269 DCHECK(oat_dex_file->source_.IsRawFile());
2270 File* raw_file = oat_dex_file->source_.GetRawFile();
2271 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2272 }
2273 Options options;
2274 options.output_to_memmap_ = true;
2275 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2276 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2277 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002278 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002279 return false;
2280 }
2281 // Set the checksum of the new oat dex file to be the original file's checksum.
2282 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2283 return true;
2284}
2285
David Brazdil7b49e6c2016-09-01 11:06:18 +01002286bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002287 File* file,
2288 OatDexFile* oat_dex_file,
2289 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002290 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2291 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002292
2293 // Extract the dex file and get the extracted size.
2294 std::string error_msg;
2295 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2296 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2297 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2298 return false;
2299 }
2300 if (file->Flush() != 0) {
2301 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2302 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2303 return false;
2304 }
2305 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2306 if (extracted_end == static_cast<off_t>(-1)) {
2307 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2308 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2309 return false;
2310 }
2311 if (extracted_end < static_cast<off_t>(start_offset)) {
2312 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2313 << " Start: " << start_offset
2314 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2315 return false;
2316 }
2317 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2318 if (extracted_size < sizeof(DexFile::Header)) {
2319 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2320 << extracted_size << " File: " << oat_dex_file->GetLocation();
2321 return false;
2322 }
2323
2324 // Read the dex file header and extract required data to OatDexFile.
2325 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2326 if (actual_offset != static_cast<off_t>(start_offset)) {
2327 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2328 << " Expected: " << start_offset
2329 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2330 return false;
2331 }
2332 if (!ReadDexFileHeader(file, oat_dex_file)) {
2333 return false;
2334 }
2335 if (extracted_size < oat_dex_file->dex_file_size_) {
2336 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2337 << " file size from header: " << oat_dex_file->dex_file_size_
2338 << " File: " << oat_dex_file->GetLocation();
2339 return false;
2340 }
2341
2342 // Override the checksum from header with the CRC from ZIP entry.
2343 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2344
2345 // Seek both file and stream to the end offset.
2346 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2347 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2348 if (actual_offset != static_cast<off_t>(end_offset)) {
2349 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2350 << " Expected: " << end_offset
2351 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2352 return false;
2353 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002354 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002355 if (actual_offset != static_cast<off_t>(end_offset)) {
2356 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2357 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2358 return false;
2359 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002360 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002361 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2362 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2363 return false;
2364 }
2365
2366 // If we extracted more than the size specified in the header, truncate the file.
2367 if (extracted_size > oat_dex_file->dex_file_size_) {
2368 if (file->SetLength(end_offset) != 0) {
2369 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002370 << " File: " << oat_dex_file->GetLocation()
2371 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002372 return false;
2373 }
2374 }
2375
2376 return true;
2377}
2378
David Brazdil7b49e6c2016-09-01 11:06:18 +01002379bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002380 File* file,
2381 OatDexFile* oat_dex_file,
2382 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002383 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2384 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002385
2386 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2387 if (input_offset != static_cast<off_t>(0)) {
2388 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2389 << " Expected: 0"
2390 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2391 return false;
2392 }
2393 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2394 return false;
2395 }
2396
2397 // Copy the input dex file using sendfile().
2398 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2399 PLOG(ERROR) << "Failed to copy dex file to oat file."
2400 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2401 return false;
2402 }
2403 if (file->Flush() != 0) {
2404 PLOG(ERROR) << "Failed to flush dex file."
2405 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2406 return false;
2407 }
2408
2409 // Check file position and seek the stream to the end offset.
2410 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2411 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2412 if (actual_offset != static_cast<off_t>(end_offset)) {
2413 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2414 << " Expected: " << end_offset
2415 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2416 return false;
2417 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002418 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002419 if (actual_offset != static_cast<off_t>(end_offset)) {
2420 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2421 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2422 return false;
2423 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002424 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002425 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2426 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2427 return false;
2428 }
2429
2430 return true;
2431}
2432
David Brazdil7b49e6c2016-09-01 11:06:18 +01002433bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002434 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002435 const uint8_t* dex_file,
2436 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002437 // Note: The raw data has already been checked to contain the header
2438 // and all the data that the header specifies as the file size.
2439 DCHECK(dex_file != nullptr);
2440 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2441 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2442
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002443 if (update_input_vdex) {
2444 // The vdex already contains the dex code, no need to write it again.
2445 } else {
2446 if (!out->WriteFully(dex_file, header->file_size_)) {
2447 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2448 << " to " << out->GetLocation();
2449 return false;
2450 }
2451 if (!out->Flush()) {
2452 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2453 << " File: " << oat_dex_file->GetLocation();
2454 return false;
2455 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002456 }
2457
2458 // Update dex file size and resize class offsets in the OatDexFile.
2459 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002460 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002461 oat_dex_file->dex_file_size_ = header->file_size_;
2462 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2463 return true;
2464}
2465
2466bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2467 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2468
David Brazdil181e1cc2016-09-01 16:38:47 +00002469 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2470 if (initial_offset == static_cast<off_t>(-1)) {
2471 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2472 return false;
2473 }
2474
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002475 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2476 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2477 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2478 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2479 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2480 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2481 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2482 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2483 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2484 return false;
2485 }
2486
2487 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2488 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2489
2490 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2491 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2492
2493 // Write OatDexFile.
2494 if (!oat_dex_file->Write(this, rodata)) {
2495 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2496 return false;
2497 }
2498 }
2499
David Brazdil181e1cc2016-09-01 16:38:47 +00002500 // Seek back to the initial position.
2501 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2502 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2503 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2504 return false;
2505 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002506
David Brazdilb92ba622016-09-01 16:00:30 +00002507 return true;
2508}
2509
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002510bool OatWriter::OpenDexFiles(
2511 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002512 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002513 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2514 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2515 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2516
2517 if (oat_dex_files_.empty()) {
2518 // Nothing to do.
2519 return true;
2520 }
2521
2522 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002523 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2524
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002525 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002526 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2527 length,
2528 PROT_READ | PROT_WRITE,
2529 MAP_SHARED,
2530 file->Fd(),
2531 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2532 /* low_4gb */ false,
2533 file->GetPath().c_str(),
2534 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002535 if (dex_files_map == nullptr) {
2536 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2537 << " error: " << error_msg;
2538 return false;
2539 }
2540 std::vector<std::unique_ptr<const DexFile>> dex_files;
2541 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2542 // Make sure no one messed with input files while we were copying data.
2543 // At the very least we need consistent file size and number of class definitions.
2544 const uint8_t* raw_dex_file =
2545 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2546 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2547 // Note: ValidateDexFileHeader() already logged an error message.
2548 LOG(ERROR) << "Failed to verify written dex file header!"
2549 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2550 << " ~ " << static_cast<const void*>(raw_dex_file);
2551 return false;
2552 }
2553 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2554 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2555 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2556 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2557 << " Output: " << file->GetPath();
2558 return false;
2559 }
2560 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2561 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2562 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2563 << " Output: " << file->GetPath();
2564 return false;
2565 }
2566
2567 // Now, open the dex file.
2568 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2569 oat_dex_file.dex_file_size_,
2570 oat_dex_file.GetLocation(),
2571 oat_dex_file.dex_file_location_checksum_,
2572 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002573 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002574 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002575 &error_msg));
2576 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002577 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2578 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002579 return false;
2580 }
2581 }
2582
2583 *opened_dex_files_map = std::move(dex_files_map);
2584 *opened_dex_files = std::move(dex_files);
2585 return true;
2586}
2587
2588bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002589 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002590 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2591 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2592
David Brazdil7b49e6c2016-09-01 11:06:18 +01002593 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2594 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2595 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2596 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2597 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2598 return false;
2599 }
2600
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002601 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2602 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2603 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002604 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2605
2606 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2607 oat_dex_file->class_offsets_.empty()) {
2608 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002609 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002610
2611 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2612 if (table_size == 0u) {
2613 continue;
2614 }
2615
2616 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002617 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002618 const DexFile& dex_file = *opened_dex_files[i];
2619 {
2620 std::unique_ptr<TypeLookupTable> type_lookup_table =
2621 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2622 type_lookup_table_oat_dex_files_.push_back(
2623 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2624 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2625 }
2626 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002627
2628 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002629 size_t initial_offset = oat_size_;
2630 size_t rodata_offset = RoundUp(initial_offset, 4);
2631 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002632
2633 if (padding_size != 0u) {
2634 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002635 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002636 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2637 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002638 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002639 return false;
2640 }
2641 }
2642
2643 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002644 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002645 DCHECK_EQ(table_size, table->RawDataLength());
2646
David Brazdil7b49e6c2016-09-01 11:06:18 +01002647 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002648 PLOG(ERROR) << "Failed to write lookup table."
2649 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002650 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002651 return false;
2652 }
2653
2654 oat_dex_file->lookup_table_offset_ = rodata_offset;
2655
David Brazdil7b49e6c2016-09-01 11:06:18 +01002656 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002657 size_oat_lookup_table_ += table_size;
2658 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002659 }
2660
David Brazdil7b49e6c2016-09-01 11:06:18 +01002661 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002662 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002663 << " File: " << oat_rodata->GetLocation();
2664 return false;
2665 }
2666
2667 return true;
2668}
2669
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002670bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002671 if (!kIsVdexEnabled) {
2672 return true;
2673 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002674 // Write checksums
2675 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2676 if (actual_offset != sizeof(VdexFile::Header)) {
2677 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2678 << " File: " << vdex_out->GetLocation();
2679 return false;
2680 }
2681
2682 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2683 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2684 if (!vdex_out->WriteFully(
2685 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2686 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2687 << vdex_out->GetLocation();
2688 return false;
2689 }
2690 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2691 }
2692
2693 // Write header.
2694 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002695 if (actual_offset != 0) {
2696 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2697 << " File: " << vdex_out->GetLocation();
2698 return false;
2699 }
2700
David Brazdil5d5a36b2016-09-14 15:34:10 +01002701 DCHECK_NE(vdex_dex_files_offset_, 0u);
2702 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2703
2704 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002705 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2706 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002707
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002708 VdexFile::Header vdex_header(oat_dex_files_.size(),
2709 dex_section_size,
2710 verifier_deps_section_size,
2711 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002712 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2713 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002714 return false;
2715 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002716 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002717
David Brazdil5d5a36b2016-09-14 15:34:10 +01002718 if (!vdex_out->Flush()) {
2719 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2720 << " File: " << vdex_out->GetLocation();
2721 return false;
2722 }
2723
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002724 return true;
2725}
2726
Vladimir Markof4da6752014-08-01 19:04:18 +01002727bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2728 static const uint8_t kPadding[] = {
2729 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2730 };
2731 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002732 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002733 return false;
2734 }
2735 size_code_alignment_ += aligned_code_delta;
2736 return true;
2737}
2738
Vladimir Marko944da602016-02-19 12:27:55 +00002739void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2740 DCHECK(dex_files_ != nullptr);
2741 DCHECK(relative_patcher_ != nullptr);
2742 DCHECK_NE(oat_data_offset_, 0u);
2743 if (image_writer_ != nullptr && !dex_files_->empty()) {
2744 // The oat data begin may not be initialized yet but the oat file offset is ready.
2745 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2746 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2747 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002748 }
2749}
2750
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002751OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2752 DexFileSource source,
2753 CreateTypeLookupTable create_type_lookup_table)
2754 : source_(source),
2755 create_type_lookup_table_(create_type_lookup_table),
2756 dex_file_size_(0),
2757 offset_(0),
2758 dex_file_location_size_(strlen(dex_file_location)),
2759 dex_file_location_data_(dex_file_location),
2760 dex_file_location_checksum_(0u),
2761 dex_file_offset_(0u),
2762 class_offsets_offset_(0u),
2763 lookup_table_offset_(0u),
2764 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002765}
2766
2767size_t OatWriter::OatDexFile::SizeOf() const {
2768 return sizeof(dex_file_location_size_)
2769 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002770 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002771 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002772 + sizeof(class_offsets_offset_)
2773 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002774}
2775
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002776void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2777 DCHECK_EQ(class_offsets_offset_, 0u);
2778 if (!class_offsets_.empty()) {
2779 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002780 size_t initial_offset = oat_writer->oat_size_;
2781 size_t offset = RoundUp(initial_offset, 4);
2782 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002783 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002784 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002785 }
2786}
2787
2788bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2789 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002790 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002791
Vladimir Markoe079e212016-05-25 12:49:49 +01002792 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002793 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002794 return false;
2795 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002796 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002797
Vladimir Markoe079e212016-05-25 12:49:49 +01002798 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002799 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002800 return false;
2801 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002802 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002803
Vladimir Markoe079e212016-05-25 12:49:49 +01002804 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002805 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002806 return false;
2807 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002808 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002809
Vladimir Markoe079e212016-05-25 12:49:49 +01002810 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002811 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002812 return false;
2813 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002814 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002815
Vladimir Markoe079e212016-05-25 12:49:49 +01002816 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002817 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2818 return false;
2819 }
2820 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2821
Vladimir Markoe079e212016-05-25 12:49:49 +01002822 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002823 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2824 return false;
2825 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002826 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002827
2828 return true;
2829}
2830
2831bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002832 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002833 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2834 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002835 return false;
2836 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002837 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002838 return true;
2839}
2840
Brian Carlstromba150c32013-08-27 17:31:03 -07002841OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002842 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002843 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002844 mirror::Class::Status status)
2845 : compiled_methods_(compiled_methods) {
2846 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002847 CHECK_LE(num_non_null_compiled_methods, num_methods);
2848
Brian Carlstrom265091e2013-01-30 14:08:26 -08002849 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002850 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2851
2852 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2853 // apply when there are 0 methods, we just arbitrarily say that 0
2854 // methods means kOatClassNoneCompiled and that we won't use
2855 // kOatClassAllCompiled unless there is at least one compiled
2856 // method. This means in an interpretter only system, we can assert
2857 // that all classes are kOatClassNoneCompiled.
2858 if (num_non_null_compiled_methods == 0) {
2859 type_ = kOatClassNoneCompiled;
2860 } else if (num_non_null_compiled_methods == num_methods) {
2861 type_ = kOatClassAllCompiled;
2862 } else {
2863 type_ = kOatClassSomeCompiled;
2864 }
2865
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002866 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002867 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002868 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002869
2870 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2871 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002872 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002873 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2874 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2875 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2876 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002877 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002878 method_bitmap_size_ = 0;
2879 }
2880
2881 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002882 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002883 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002884 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2885 } else {
2886 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2887 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2888 if (type_ == kOatClassSomeCompiled) {
2889 method_bitmap_->SetBit(i);
2890 }
2891 }
2892 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002893}
2894
Brian Carlstrom265091e2013-01-30 14:08:26 -08002895size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2896 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002897 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2898 if (method_offset == 0) {
2899 return 0;
2900 }
2901 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002902}
2903
2904size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2905 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002906 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002907}
2908
2909size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002910 return sizeof(status_)
2911 + sizeof(type_)
2912 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2913 + method_bitmap_size_
2914 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002915}
2916
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002917bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002918 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002919 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002920 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002921 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002922 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002923 return false;
2924 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002925 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002926
Vladimir Markoe079e212016-05-25 12:49:49 +01002927 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002928 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002929 return false;
2930 }
2931 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002932
Brian Carlstromba150c32013-08-27 17:31:03 -07002933 if (method_bitmap_size_ != 0) {
2934 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002935 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002936 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002937 return false;
2938 }
2939 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002940
Vladimir Markoe079e212016-05-25 12:49:49 +01002941 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002942 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002943 return false;
2944 }
2945 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2946 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002947
Vladimir Markoe079e212016-05-25 12:49:49 +01002948 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002949 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002950 return false;
2951 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002952 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002953 return true;
2954}
2955
Brian Carlstrome24fa612011-09-29 00:53:55 -07002956} // namespace art