blob: c60b02a2276923fdb5fb4aca40010ac387ba3fd2 [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"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000026#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070029#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070030#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000031#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000032#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000033#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "dex_file-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000035#include "driver/compiler_driver.h"
36#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010037#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030039#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010040#include "image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000041#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000042#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/array.h"
44#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010045#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010047#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070048#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070049#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010052#include "utils/dex_cache_arrays_layout-inl.h"
jeffhaoec014232012-09-05 10:42:25 -070053#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000054#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070055
56namespace art {
57
Vladimir Marko9bdf1082016-01-21 12:15:52 +000058namespace { // anonymous namespace
59
60typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
61
62const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
63 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
64}
65
66} // anonymous namespace
67
68// Defines the location of the raw dex file to write.
69class OatWriter::DexFileSource {
70 public:
71 explicit DexFileSource(ZipEntry* zip_entry)
72 : type_(kZipEntry), source_(zip_entry) {
73 DCHECK(source_ != nullptr);
74 }
75
76 explicit DexFileSource(File* raw_file)
77 : type_(kRawFile), source_(raw_file) {
78 DCHECK(source_ != nullptr);
79 }
80
81 explicit DexFileSource(const uint8_t* dex_file)
82 : type_(kRawData), source_(dex_file) {
83 DCHECK(source_ != nullptr);
84 }
85
86 bool IsZipEntry() const { return type_ == kZipEntry; }
87 bool IsRawFile() const { return type_ == kRawFile; }
88 bool IsRawData() const { return type_ == kRawData; }
89
90 ZipEntry* GetZipEntry() const {
91 DCHECK(IsZipEntry());
92 DCHECK(source_ != nullptr);
93 return static_cast<ZipEntry*>(const_cast<void*>(source_));
94 }
95
96 File* GetRawFile() const {
97 DCHECK(IsRawFile());
98 DCHECK(source_ != nullptr);
99 return static_cast<File*>(const_cast<void*>(source_));
100 }
101
102 const uint8_t* GetRawData() const {
103 DCHECK(IsRawData());
104 DCHECK(source_ != nullptr);
105 return static_cast<const uint8_t*>(source_);
106 }
107
108 void Clear() {
109 type_ = kNone;
110 source_ = nullptr;
111 }
112
113 private:
114 enum Type {
115 kNone,
116 kZipEntry,
117 kRawFile,
118 kRawData,
119 };
120
121 Type type_;
122 const void* source_;
123};
124
Vladimir Marko49b0f452015-12-10 13:49:19 +0000125class OatWriter::OatClass {
126 public:
127 OatClass(size_t offset,
128 const dchecked_vector<CompiledMethod*>& compiled_methods,
129 uint32_t num_non_null_compiled_methods,
130 mirror::Class::Status status);
131 OatClass(OatClass&& src) = default;
132 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
133 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
134 size_t SizeOf() const;
135 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
136
137 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
138 return compiled_methods_[class_def_method_index];
139 }
140
141 // Offset of start of OatClass from beginning of OatHeader. It is
142 // used to validate file position when writing.
143 size_t offset_;
144
145 // CompiledMethods for each class_def_method_index, or null if no method is available.
146 dchecked_vector<CompiledMethod*> compiled_methods_;
147
148 // Offset from OatClass::offset_ to the OatMethodOffsets for the
149 // class_def_method_index. If 0, it means the corresponding
150 // CompiledMethod entry in OatClass::compiled_methods_ should be
151 // null and that the OatClass::type_ should be kOatClassBitmap.
152 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
153
154 // Data to write.
155
156 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
157 int16_t status_;
158
159 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
160 uint16_t type_;
161
162 uint32_t method_bitmap_size_;
163
164 // bit vector indexed by ClassDef method index. When
165 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
166 // method has an OatMethodOffsets in methods_offsets_, otherwise
167 // the entry was ommited to save space. If OatClassType::type_ is
168 // not is kOatClassBitmap, the bitmap will be null.
169 std::unique_ptr<BitVector> method_bitmap_;
170
171 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
172 // present in the OatClass. Note that some may be missing if
173 // OatClass::compiled_methods_ contains null values (and
174 // oat_method_offsets_offsets_from_oat_class_ should contain 0
175 // values in this case).
176 dchecked_vector<OatMethodOffsets> method_offsets_;
177 dchecked_vector<OatQuickMethodHeader> method_headers_;
178
179 private:
180 size_t GetMethodOffsetsRawSize() const {
181 return method_offsets_.size() * sizeof(method_offsets_[0]);
182 }
183
184 DISALLOW_COPY_AND_ASSIGN(OatClass);
185};
186
187class OatWriter::OatDexFile {
188 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000189 OatDexFile(const char* dex_file_location,
190 DexFileSource source,
191 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000192 OatDexFile(OatDexFile&& src) = default;
193
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000194 const char* GetLocation() const {
195 return dex_file_location_data_;
196 }
197
198 void ReserveTypeLookupTable(OatWriter* oat_writer);
199 void ReserveClassOffsets(OatWriter* oat_writer);
200
Vladimir Marko49b0f452015-12-10 13:49:19 +0000201 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000202 bool Write(OatWriter* oat_writer, OutputStream* out) const;
203 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
204
205 // The source of the dex file.
206 DexFileSource source_;
207
208 // Whether to create the type lookup table.
209 CreateTypeLookupTable create_type_lookup_table_;
210
211 // Dex file size. Initialized when writing the dex file.
212 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000213
214 // Offset of start of OatDexFile from beginning of OatHeader. It is
215 // used to validate file position when writing.
216 size_t offset_;
217
218 // Data to write.
219 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000220 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000221 uint32_t dex_file_location_checksum_;
222 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000223 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000224 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225
226 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000227 dchecked_vector<uint32_t> class_offsets_;
228
229 private:
230 size_t GetClassOffsetsRawSize() const {
231 return class_offsets_.size() * sizeof(class_offsets_[0]);
232 }
233
234 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
235};
236
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100237#define DCHECK_OFFSET() \
238 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
239 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
240
241#define DCHECK_OFFSET_() \
242 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
243 << "file_offset=" << file_offset << " offset_=" << offset_
244
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000245OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
246 : write_state_(WriteState::kAddingDexFileSources),
247 timings_(timings),
248 raw_dex_files_(),
249 zip_archives_(),
250 zipped_dex_files_(),
251 zipped_dex_file_locations_(),
252 compiler_driver_(nullptr),
253 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800254 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100256 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000257 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100258 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700259 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700260 size_dex_file_alignment_(0),
261 size_executable_offset_alignment_(0),
262 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700263 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700264 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700265 size_interpreter_to_interpreter_bridge_(0),
266 size_interpreter_to_compiled_code_bridge_(0),
267 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800268 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700269 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700270 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700271 size_quick_to_interpreter_bridge_(0),
272 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100273 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700274 size_code_(0),
275 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100276 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100277 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700278 size_mapping_table_(0),
279 size_vmap_table_(0),
280 size_gc_map_(0),
281 size_oat_dex_file_location_size_(0),
282 size_oat_dex_file_location_data_(0),
283 size_oat_dex_file_location_checksum_(0),
284 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000285 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000286 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000287 size_oat_lookup_table_alignment_(0),
288 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000289 size_oat_class_offsets_alignment_(0),
290 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700291 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700292 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700293 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100294 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000295 relative_patcher_(nullptr),
296 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000297}
298
299bool OatWriter::AddDexFileSource(const char* filename,
300 const char* location,
301 CreateTypeLookupTable create_type_lookup_table) {
302 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
303 uint32_t magic;
304 std::string error_msg;
305 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
306 if (fd.get() == -1) {
307 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
308 return false;
309 } else if (IsDexMagic(magic)) {
310 // The file is open for reading, not writing, so it's OK to let the File destructor
311 // close it without checking for explicit Close(), so pass checkUsage = false.
312 raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
313 oat_dex_files_.emplace_back(location,
314 DexFileSource(raw_dex_files_.back().get()),
315 create_type_lookup_table);
316 } else if (IsZipMagic(magic)) {
317 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
318 return false;
319 }
320 } else {
321 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
322 return false;
323 }
324 return true;
325}
326
327// Add dex file source(s) from a zip file specified by a file handle.
328bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
329 const char* location,
330 CreateTypeLookupTable create_type_lookup_table) {
331 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
332 std::string error_msg;
333 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
334 ZipArchive* zip_archive = zip_archives_.back().get();
335 if (zip_archive == nullptr) {
336 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
337 << error_msg;
338 return false;
339 }
340 for (size_t i = 0; ; ++i) {
341 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
342 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
343 if (entry == nullptr) {
344 break;
345 }
346 zipped_dex_files_.push_back(std::move(entry));
347 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
348 const char* full_location = zipped_dex_file_locations_.back().c_str();
349 oat_dex_files_.emplace_back(full_location,
350 DexFileSource(zipped_dex_files_.back().get()),
351 create_type_lookup_table);
352 }
353 if (zipped_dex_file_locations_.empty()) {
354 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
355 return false;
356 }
357 return true;
358}
359
360// Add dex file source from raw memory.
361bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
362 const char* location,
363 uint32_t location_checksum,
364 CreateTypeLookupTable create_type_lookup_table) {
365 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
366 if (data.size() < sizeof(DexFile::Header)) {
367 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
368 << data.size() << " File: " << location;
369 return false;
370 }
371 if (!ValidateDexFileHeader(data.data(), location)) {
372 return false;
373 }
374 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
375 if (data.size() < header->file_size_) {
376 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
377 << " file size from header: " << header->file_size_ << " File: " << location;
378 return false;
379 }
380
381 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
382 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
383 return true;
384}
385
386dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
387 dchecked_vector<const char*> locations;
388 locations.reserve(oat_dex_files_.size());
389 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
390 locations.push_back(oat_dex_file.GetLocation());
391 }
392 return locations;
393}
394
395bool OatWriter::WriteAndOpenDexFiles(
396 OutputStream* rodata,
397 File* file,
398 InstructionSet instruction_set,
399 const InstructionSetFeatures* instruction_set_features,
400 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800401 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000402 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
403 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
404 CHECK(write_state_ == WriteState::kAddingDexFileSources);
405
406 size_t offset = InitOatHeader(instruction_set,
407 instruction_set_features,
408 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
409 key_value_store);
410 offset = InitOatDexFiles(offset);
411 size_ = offset;
412
413 std::unique_ptr<MemMap> dex_files_map;
414 std::vector<std::unique_ptr<const DexFile>> dex_files;
415 if (!WriteDexFiles(rodata, file)) {
416 return false;
417 }
418 // Reserve space for type lookup tables and update type_lookup_table_offset_.
419 for (OatDexFile& oat_dex_file : oat_dex_files_) {
420 oat_dex_file.ReserveTypeLookupTable(this);
421 }
422 size_t size_after_type_lookup_tables = size_;
423 // Reserve space for class offsets and update class_offsets_offset_.
424 for (OatDexFile& oat_dex_file : oat_dex_files_) {
425 oat_dex_file.ReserveClassOffsets(this);
426 }
427 if (!WriteOatDexFiles(rodata) ||
428 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800429 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000430 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
431 return false;
432 }
433
434 *opened_dex_files_map = std::move(dex_files_map);
435 *opened_dex_files = std::move(dex_files);
436 write_state_ = WriteState::kPrepareLayout;
437 return true;
438}
439
440void OatWriter::PrepareLayout(const CompilerDriver* compiler,
441 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000442 const std::vector<const DexFile*>& dex_files,
443 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 CHECK(write_state_ == WriteState::kPrepareLayout);
445
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000446 compiler_driver_ = compiler;
447 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000448 dex_files_ = &dex_files;
449 relative_patcher_ = relative_patcher;
450 SetMultiOatRelativePatcherAdjustment();
451
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 if (compiling_boot_image_) {
453 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800454 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100455 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000456 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100457
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000458 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800459 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000460 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800461 offset = InitOatClasses(offset);
462 }
463 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000464 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100465 offset = InitOatMaps(offset);
466 }
467 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000468 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800469 offset = InitOatCode(offset);
470 }
471 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000472 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800473 offset = InitOatCodeDexFiles(offset);
474 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700475 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700476
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800477 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100478 // Allocate space for app dex cache arrays in the .bss section.
479 size_t bss_start = RoundUp(size_, kPageSize);
480 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
481 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000482 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100483 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
484 DexCacheArraysLayout layout(pointer_size, dex_file);
485 bss_size_ += layout.Size();
486 }
487 }
488
Brian Carlstrome24fa612011-09-29 00:53:55 -0700489 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800490 if (compiling_boot_image_) {
491 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800493 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000494
495 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700496}
497
Ian Rogers0571d352011-11-03 19:51:38 -0700498OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700499}
500
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100501struct OatWriter::GcMapDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100502 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100503 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100504 }
505
506 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800507 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
508 return offset == 0u ? 0u :
509 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100510 }
511
512 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
513 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800514 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
515 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100516 }
517
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800518 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100519 return "GC map";
520 }
521};
522
523struct OatWriter::MappingTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100524 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000525 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100526 }
527
528 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100529 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
530 return offset == 0u ? 0u :
531 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100532 }
533
534 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
535 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100536 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
537 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100538 }
539
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800540 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100541 return "mapping table";
542 }
543};
544
545struct OatWriter::VmapTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100546 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800547 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100548 }
549
550 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100551 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
552 return offset == 0u ? 0u :
553 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100554 }
555
556 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
557 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100558 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
559 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100560 }
561
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800562 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100563 return "vmap table";
564 }
565};
566
567class OatWriter::DexMethodVisitor {
568 public:
569 DexMethodVisitor(OatWriter* writer, size_t offset)
570 : writer_(writer),
571 offset_(offset),
572 dex_file_(nullptr),
573 class_def_index_(DexFile::kDexNoIndex) {
574 }
575
576 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
577 DCHECK(dex_file_ == nullptr);
578 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
579 dex_file_ = dex_file;
580 class_def_index_ = class_def_index;
581 return true;
582 }
583
584 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
585
586 virtual bool EndClass() {
587 if (kIsDebugBuild) {
588 dex_file_ = nullptr;
589 class_def_index_ = DexFile::kDexNoIndex;
590 }
591 return true;
592 }
593
594 size_t GetOffset() const {
595 return offset_;
596 }
597
598 protected:
599 virtual ~DexMethodVisitor() { }
600
601 OatWriter* const writer_;
602
603 // The offset is usually advanced for each visited method by the derived class.
604 size_t offset_;
605
606 // The dex file and class def index are set in StartClass().
607 const DexFile* dex_file_;
608 size_t class_def_index_;
609};
610
611class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
612 public:
613 OatDexMethodVisitor(OatWriter* writer, size_t offset)
614 : DexMethodVisitor(writer, offset),
615 oat_class_index_(0u),
616 method_offsets_index_(0u) {
617 }
618
619 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
620 DexMethodVisitor::StartClass(dex_file, class_def_index);
621 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
622 method_offsets_index_ = 0u;
623 return true;
624 }
625
626 bool EndClass() {
627 ++oat_class_index_;
628 return DexMethodVisitor::EndClass();
629 }
630
631 protected:
632 size_t oat_class_index_;
633 size_t method_offsets_index_;
634};
635
636class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
637 public:
638 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
639 : DexMethodVisitor(writer, offset),
640 compiled_methods_(),
641 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000642 size_t num_classes = 0u;
643 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
644 num_classes += oat_dex_file.class_offsets_.size();
645 }
646 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100647 compiled_methods_.reserve(256u);
648 }
649
650 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
651 DexMethodVisitor::StartClass(dex_file, class_def_index);
652 compiled_methods_.clear();
653 num_non_null_compiled_methods_ = 0u;
654 return true;
655 }
656
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300657 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
658 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100659 // Fill in the compiled_methods_ array for methods that have a
660 // CompiledMethod. We track the number of non-null entries in
661 // num_non_null_compiled_methods_ since we only want to allocate
662 // OatMethodOffsets for the compiled methods.
663 uint32_t method_idx = it.GetMemberIndex();
664 CompiledMethod* compiled_method =
665 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
666 compiled_methods_.push_back(compiled_method);
667 if (compiled_method != nullptr) {
668 ++num_non_null_compiled_methods_;
669 }
670 return true;
671 }
672
673 bool EndClass() {
674 ClassReference class_ref(dex_file_, class_def_index_);
675 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
676 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700677 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100678 status = compiled_class->GetStatus();
679 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
680 status = mirror::Class::kStatusError;
681 } else {
682 status = mirror::Class::kStatusNotReady;
683 }
684
Vladimir Marko49b0f452015-12-10 13:49:19 +0000685 writer_->oat_classes_.emplace_back(offset_,
686 compiled_methods_,
687 num_non_null_compiled_methods_,
688 status);
689 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100690 return DexMethodVisitor::EndClass();
691 }
692
693 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000694 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100695 size_t num_non_null_compiled_methods_;
696};
697
698class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
699 public:
700 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100701 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100702 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100703 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100704 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
705 }
706
707 bool EndClass() {
708 OatDexMethodVisitor::EndClass();
709 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100710 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100711 }
712 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100713 }
714
715 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700716 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000717 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
719
720 if (compiled_method != nullptr) {
721 // Derived from CompiledMethod.
722 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723
Vladimir Marko35831e82015-09-11 11:59:18 +0100724 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
725 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800726 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800727
David Srbecky009e2a62015-04-15 02:46:30 +0100728 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Markoc74658b2015-03-31 10:26:41 +0100729 bool deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800730 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000731 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000732 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
733 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800734 // Duplicate methods, we want the same code for both of them so that the oat writer puts
735 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800736 deduped = true;
737 } else {
738 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
739 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000740 } else {
741 auto lb = dedupe_map_.lower_bound(compiled_method);
742 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
743 quick_code_offset = lb->second;
744 deduped = true;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000745 } else {
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000746 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
747 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
David Srbecky009e2a62015-04-15 02:46:30 +0100748 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800749 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100750
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100751 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000752 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100753 // TODO: Should this be a hard failure?
754 LOG(WARNING) << "Multiple definitions of "
755 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000756 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
757 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100758 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000759 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100760 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800761 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762
Elliott Hughes956af0f2014-12-11 14:34:28 -0800763 // Update quick method header.
764 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
765 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
766 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
767 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100768 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
769 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100770 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800771 uint32_t gc_map_offset = method_header->gc_map_offset_;
772 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
773 // to 0-offset and we need to adjust it by code_offset.
774 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100775 if (mapping_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800776 mapping_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100777 DCHECK_LT(mapping_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800778 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100779 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800780 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100781 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800782 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100783 if (gc_map_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800784 gc_map_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100785 DCHECK_LT(gc_map_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800786 }
787 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
788 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
789 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
790 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
791 gc_map_offset, frame_size_in_bytes, core_spill_mask,
792 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100793
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000794 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800795 // Update offsets. (Checksum is updated when writing.)
796 offset_ += sizeof(*method_header); // Method header is prepended before code.
797 offset_ += code_size;
798 // Record absolute patch locations.
799 if (!compiled_method->GetPatches().empty()) {
800 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
801 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000802 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100803 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100804 }
805 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 }
Alex Light78382fa2014-06-06 15:45:32 -0700808
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000809 if (writer_->compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800810 // Record debug information for this function if we are doing that.
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 const uint32_t quick_code_start = quick_code_offset -
David Srbecky6f715892015-03-30 14:21:42 +0100812 writer_->oat_header_->GetExecutableOffset() - thumb_offset;
David Srbeckyc5bfa972016-02-05 15:49:10 +0000813 writer_->method_info_.push_back(debug::MethodDebugInfo {
David Srbecky0df9e1f2015-04-07 19:02:58 +0100814 dex_file_,
815 class_def_index_,
816 it.GetMemberIndex(),
817 it.GetMethodAccessFlags(),
818 it.GetMethodCodeItem(),
819 deduped,
820 quick_code_start,
821 quick_code_start + code_size,
822 compiled_method});
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100823 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100824
825 if (kIsDebugBuild) {
826 // We expect GC maps except when the class hasn't been verified or the method is native.
827 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
828 ClassReference class_ref(dex_file_, class_def_index_);
829 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
830 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700831 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832 status = compiled_class->GetStatus();
833 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
834 status = mirror::Class::kStatusError;
835 } else {
836 status = mirror::Class::kStatusNotReady;
837 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100838 ArrayRef<const uint8_t> gc_map = compiled_method->GetGcMap();
839 if (!gc_map.empty()) {
840 size_t gc_map_size = gc_map.size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700841 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100842 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
Vladimir Marko35831e82015-09-11 11:59:18 +0100843 << gc_map_size << " " << (is_native ? "true" : "false") << " "
Nicolas Geoffray39468442014-09-02 15:17:15 +0100844 << (status < mirror::Class::kStatusVerified) << " " << status << " "
845 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
846 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100847 }
848
849 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
850 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
851 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100852 ++method_offsets_index_;
853 }
854
855 return true;
856 }
857
858 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000859 struct CodeOffsetsKeyComparator {
860 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100861 // Code is deduplicated by CompilerDriver, compare only data pointers.
862 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
863 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000864 }
865 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100866 if (UNLIKELY(lhs->GetMappingTable().data() != rhs->GetMappingTable().data())) {
867 return lhs->GetMappingTable().data() < rhs->GetMappingTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000868 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100869 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
870 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000871 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100872 if (UNLIKELY(lhs->GetGcMap().data() != rhs->GetGcMap().data())) {
873 return lhs->GetGcMap().data() < rhs->GetGcMap().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000874 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100875 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
876 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000877 }
878 return false;
879 }
880 };
881
David Srbecky009e2a62015-04-15 02:46:30 +0100882 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
883 const ClassDataItemIterator& it,
884 uint32_t thumb_offset) {
885 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100886 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100887 offset_ = compiled_method->AlignCode(offset_);
888 DCHECK_ALIGNED_PARAM(offset_,
889 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
890 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
891 }
892
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100893 // Deduplication is already done on a pointer basis by the compiler driver,
894 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100895 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100896
David Srbecky009e2a62015-04-15 02:46:30 +0100897 // Cache of compiler's --debuggable option.
898 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100899};
900
901template <typename DataAccess>
902class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
903 public:
904 InitMapMethodVisitor(OatWriter* writer, size_t offset)
905 : OatDexMethodVisitor(writer, offset) {
906 }
907
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700908 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700909 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000910 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100911 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
912
913 if (compiled_method != nullptr) {
914 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
915 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
916
Vladimir Marko35831e82015-09-11 11:59:18 +0100917 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
918 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100919 if (map_size != 0u) {
Vladimir Marko35831e82015-09-11 11:59:18 +0100920 auto lb = dedupe_map_.lower_bound(map.data());
921 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map.data(), lb->first)) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100922 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923 } else {
924 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Marko35831e82015-09-11 11:59:18 +0100925 dedupe_map_.PutBefore(lb, map.data(), offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100926 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100927 }
928 }
929 ++method_offsets_index_;
930 }
931
932 return true;
933 }
934
935 private:
936 // Deduplication is already done on a pointer basis by the compiler driver,
937 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100938 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939};
940
941class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
942 public:
943 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800944 : OatDexMethodVisitor(writer, offset),
945 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946 }
947
948 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700949 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800950 const DexFile::TypeId& type_id =
951 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
952 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
953 // Skip methods that are not in the image.
954 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
955 return true;
956 }
957
Vladimir Marko49b0f452015-12-10 13:49:19 +0000958 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
960
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800961 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100962 if (compiled_method != nullptr) {
963 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
964 offsets = oat_class->method_offsets_[method_offsets_index_];
965 ++method_offsets_index_;
966 }
967
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100968 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969 // Unchecked as we hold mutator_lock_ on entry.
970 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800971 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700972 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
973 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800974 ArtMethod* method;
975 if (writer_->HasBootImage()) {
976 const InvokeType invoke_type = it.GetMethodInvokeType(
977 dex_file_->GetClassDef(class_def_index_));
978 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
979 *dex_file_,
980 it.GetMemberIndex(),
981 dex_cache,
982 ScopedNullHandle<mirror::ClassLoader>(),
983 nullptr,
984 invoke_type);
985 if (method == nullptr) {
986 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
987 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
988 soa.Self()->AssertPendingException();
989 mirror::Throwable* exc = soa.Self()->GetException();
990 std::string dump = exc->Dump();
991 LOG(FATAL) << dump;
992 UNREACHABLE();
993 }
994 } else {
995 // Should already have been resolved by the compiler, just peek into the dex cache.
996 // It may not be resolved if the class failed to verify, in this case, don't set the
997 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
998 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700999 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001000 if (method != nullptr &&
1001 compiled_method != nullptr &&
1002 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001003 method->SetEntryPointFromQuickCompiledCodePtrSize(
1004 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1005 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001006
1007 return true;
1008 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001009
1010 protected:
1011 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001012};
1013
1014class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1015 public:
1016 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001017 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001018 : OatDexMethodVisitor(writer, relative_offset),
1019 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001020 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001021 soa_(Thread::Current()),
1022 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001023 class_linker_(Runtime::Current()->GetClassLinker()),
1024 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001025 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001026 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001027 // If we're creating the image, the address space must be ready so that we can apply patches.
1028 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001029 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001030 }
1031
Vladimir Markof4da6752014-08-01 19:04:18 +01001032 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001033 }
1034
1035 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -07001036 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001037 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1038 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001039 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markof4da6752014-08-01 19:04:18 +01001040 }
1041 return true;
1042 }
1043
Mathieu Chartier90443472015-07-16 20:32:27 -07001044 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001045 bool result = OatDexMethodVisitor::EndClass();
1046 if (oat_class_index_ == writer_->oat_classes_.size()) {
1047 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001048 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001049 if (UNLIKELY(offset_ == 0u)) {
1050 PLOG(ERROR) << "Failed to write final relative call thunks";
1051 result = false;
1052 }
1053 }
1054 return result;
1055 }
1056
1057 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -07001058 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001059 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001060 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1061
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001062 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1063 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001064 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001065 size_t file_offset = file_offset_;
1066 OutputStream* out = out_;
1067
Vladimir Marko35831e82015-09-11 11:59:18 +01001068 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1069 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001070
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001071 // Deduplicate code arrays.
1072 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1073 if (method_offsets.code_offset_ > offset_) {
1074 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1075 if (offset_ == 0u) {
1076 ReportWriteFailure("relative call thunk", it);
1077 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001078 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001079 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1080 uint32_t aligned_code_delta = aligned_offset - offset_;
1081 if (aligned_code_delta != 0) {
1082 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1083 ReportWriteFailure("code alignment padding", it);
1084 return false;
1085 }
1086 offset_ += aligned_code_delta;
1087 DCHECK_OFFSET_();
1088 }
1089 DCHECK_ALIGNED_PARAM(offset_,
1090 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1091 DCHECK_EQ(method_offsets.code_offset_,
1092 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1093 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1094 const OatQuickMethodHeader& method_header =
1095 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +00001096 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001097 ReportWriteFailure("method header", it);
1098 return false;
1099 }
1100 writer_->size_method_header_ += sizeof(method_header);
1101 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001102 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001103
1104 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001105 patched_code_.assign(quick_code.begin(), quick_code.end());
1106 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001107 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001108 uint32_t literal_offset = patch.LiteralOffset();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001109 if (patch.Type() == kLinkerPatchCallRelative) {
1110 // NOTE: Relative calls across oat files are not supported.
1111 uint32_t target_offset = GetTargetOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001112 writer_->relative_patcher_->PatchCall(&patched_code_,
1113 literal_offset,
1114 offset_ + literal_offset,
1115 target_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001116 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1117 uint32_t target_offset = GetDexCacheOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001118 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_,
1119 patch,
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001120 offset_ + literal_offset,
1121 target_offset);
1122 } else if (patch.Type() == kLinkerPatchCall) {
1123 uint32_t target_offset = GetTargetOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001124 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001125 } else if (patch.Type() == kLinkerPatchMethod) {
1126 ArtMethod* method = GetTargetMethod(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001127 PatchMethodAddress(&patched_code_, literal_offset, method);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001128 } else if (patch.Type() == kLinkerPatchType) {
1129 mirror::Class* type = GetTargetType(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001130 PatchObjectAddress(&patched_code_, literal_offset, type);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001131 }
1132 }
1133 }
1134
Vladimir Marko49b0f452015-12-10 13:49:19 +00001135 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001136 ReportWriteFailure("method code", it);
1137 return false;
1138 }
1139 writer_->size_code_ += code_size;
1140 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001141 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001142 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001143 ++method_offsets_index_;
1144 }
1145
1146 return true;
1147 }
1148
1149 private:
1150 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001151 const size_t file_offset_;
1152 const ScopedObjectAccess soa_;
1153 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001154 ClassLinker* const class_linker_;
1155 mirror::DexCache* dex_cache_;
1156 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001157
1158 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1159 PLOG(ERROR) << "Failed to write " << what << " for "
1160 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1161 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001162
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001164 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001165 MethodReference ref = patch.TargetMethod();
1166 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001167 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1168 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001169 ArtMethod* method = dex_cache->GetResolvedMethod(
1170 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001171 CHECK(method != nullptr);
1172 return method;
1173 }
1174
Mathieu Chartier90443472015-07-16 20:32:27 -07001175 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001176 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1177 // If there's no new compiled code, either we're compiling an app and the target method
1178 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001179 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001180 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001181 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001182 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1183 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1184 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001185 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001186 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1187 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1188 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1189 target_offset = PointerToLowMemUInt32(oat_code_offset);
1190 } else {
1191 target_offset = target->IsNative()
1192 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1193 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1194 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001195 }
1196 return target_offset;
1197 }
1198
1199 mirror::Class* GetTargetType(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001200 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001201 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001202 ? dex_cache_ : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001203 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1204 CHECK(type != nullptr);
1205 return type;
1206 }
1207
Mathieu Chartier90443472015-07-16 20:32:27 -07001208 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001209 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001210 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1211 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1212 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1213 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001214 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001215 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001216 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1217 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001218 }
1219 }
1220
Vladimir Markof4da6752014-08-01 19:04:18 +01001221 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001222 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001223 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001224 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001225 } else {
1226 // NOTE: We're using linker patches for app->boot references when the image can
1227 // be relocated and therefore we need to emit .oat_patches. We're not using this
1228 // for app->app references, so check that the object is in the image space.
1229 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001230 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001231 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001232 uint32_t address = PointerToLowMemUInt32(object);
1233 DCHECK_LE(offset + 4, code->size());
1234 uint8_t* data = &(*code)[offset];
1235 data[0] = address & 0xffu;
1236 data[1] = (address >> 8) & 0xffu;
1237 data[2] = (address >> 16) & 0xffu;
1238 data[3] = (address >> 24) & 0xffu;
1239 }
1240
Mathieu Chartiere401d142015-04-22 13:56:20 -07001241 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001242 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001243 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001244 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001245 } else if (kIsDebugBuild) {
1246 // NOTE: We're using linker patches for app->boot references when the image can
1247 // be relocated and therefore we need to emit .oat_patches. We're not using this
1248 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001249 std::vector<gc::space::ImageSpace*> image_spaces =
1250 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1251 bool contains_method = false;
1252 for (gc::space::ImageSpace* image_space : image_spaces) {
1253 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1254 contains_method |=
1255 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1256 }
1257 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001258 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001259 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001260 uint32_t address = PointerToLowMemUInt32(method);
1261 DCHECK_LE(offset + 4, code->size());
1262 uint8_t* data = &(*code)[offset];
1263 data[0] = address & 0xffu;
1264 data[1] = (address >> 8) & 0xffu;
1265 data[2] = (address >> 16) & 0xffu;
1266 data[3] = (address >> 24) & 0xffu;
1267 }
1268
Vladimir Markof4da6752014-08-01 19:04:18 +01001269 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001270 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001271 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001272 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001273 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1274 // TODO: Clean up offset types.
1275 // The target_offset must be treated as signed for cross-oat patching.
1276 const void* target = reinterpret_cast<const void*>(
1277 writer_->image_writer_->GetOatDataBegin(oat_index) +
1278 static_cast<int32_t>(target_offset));
1279 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001280 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001281 DCHECK_LE(offset + 4, code->size());
1282 uint8_t* data = &(*code)[offset];
1283 data[0] = address & 0xffu;
1284 data[1] = (address >> 8) & 0xffu;
1285 data[2] = (address >> 16) & 0xffu;
1286 data[3] = (address >> 24) & 0xffu;
1287 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001288};
1289
1290template <typename DataAccess>
1291class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1292 public:
1293 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001294 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001295 : OatDexMethodVisitor(writer, relative_offset),
1296 out_(out),
1297 file_offset_(file_offset) {
1298 }
1299
1300 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001301 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001302 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1303
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001304 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001305 size_t file_offset = file_offset_;
1306 OutputStream* out = out_;
1307
1308 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1309 ++method_offsets_index_;
1310
1311 // Write deduplicated map.
Vladimir Marko35831e82015-09-11 11:59:18 +01001312 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
1313 size_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001314 DCHECK((map_size == 0u && map_offset == 0u) ||
1315 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001316 << map_size << " " << map_offset << " " << offset_ << " "
1317 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001318 if (map_size != 0u && map_offset == offset_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001319 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001320 ReportWriteFailure(it);
1321 return false;
1322 }
1323 offset_ += map_size;
1324 }
1325 DCHECK_OFFSET_();
1326 }
1327
1328 return true;
1329 }
1330
1331 private:
1332 OutputStream* const out_;
1333 size_t const file_offset_;
1334
1335 void ReportWriteFailure(const ClassDataItemIterator& it) {
1336 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1337 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1338 }
1339};
1340
1341// Visit all methods from all classes in all dex files with the specified visitor.
1342bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1343 for (const DexFile* dex_file : *dex_files_) {
1344 const size_t class_def_count = dex_file->NumClassDefs();
1345 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1346 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1347 return false;
1348 }
1349 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001350 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001351 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001352 ClassDataItemIterator it(*dex_file, class_data);
1353 while (it.HasNextStaticField()) {
1354 it.Next();
1355 }
1356 while (it.HasNextInstanceField()) {
1357 it.Next();
1358 }
1359 size_t class_def_method_index = 0u;
1360 while (it.HasNextDirectMethod()) {
1361 if (!visitor->VisitMethod(class_def_method_index, it)) {
1362 return false;
1363 }
1364 ++class_def_method_index;
1365 it.Next();
1366 }
1367 while (it.HasNextVirtualMethod()) {
1368 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1369 return false;
1370 }
1371 ++class_def_method_index;
1372 it.Next();
1373 }
1374 }
1375 if (UNLIKELY(!visitor->EndClass())) {
1376 return false;
1377 }
1378 }
1379 }
1380 return true;
1381}
1382
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001383size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1384 const InstructionSetFeatures* instruction_set_features,
1385 uint32_t num_dex_files,
1386 SafeMap<std::string, std::string>* key_value_store) {
1387 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1388 oat_header_.reset(OatHeader::Create(instruction_set,
1389 instruction_set_features,
1390 num_dex_files,
1391 key_value_store));
1392 size_oat_header_ += sizeof(OatHeader);
1393 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001394 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001395}
1396
1397size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001398 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1399 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001400 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001401 oat_dex_file.offset_ = offset;
1402 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001403 }
1404 return offset;
1405}
1406
Brian Carlstrom389efb02012-01-11 12:06:26 -08001407size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001408 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001409 InitOatClassesMethodVisitor visitor(this, offset);
1410 bool success = VisitDexMethods(&visitor);
1411 CHECK(success);
1412 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001413
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001414 // Update oat_dex_files_.
1415 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001416 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1417 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001418 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001419 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001421 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001422 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 CHECK(oat_class_it == oat_classes_.end());
1424
1425 return offset;
1426}
1427
1428size_t OatWriter::InitOatMaps(size_t offset) {
1429 #define VISIT(VisitorType) \
1430 do { \
1431 VisitorType visitor(this, offset); \
1432 bool success = VisitDexMethods(&visitor); \
1433 DCHECK(success); \
1434 offset = visitor.GetOffset(); \
1435 } while (false)
1436
1437 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1438 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1439 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1440
1441 #undef VISIT
1442
Brian Carlstrome24fa612011-09-29 00:53:55 -07001443 return offset;
1444}
1445
1446size_t OatWriter::InitOatCode(size_t offset) {
1447 // calculate the offsets within OatHeader to executable code
1448 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001449 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001450 // required to be on a new page boundary
1451 offset = RoundUp(offset, kPageSize);
1452 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001453 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001454 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001455 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001456
Ian Rogers848871b2013-08-05 10:56:33 -07001457 #define DO_TRAMPOLINE(field, fn_name) \
1458 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001459 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1460 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001461 field.reset(compiler_driver_->Create ## fn_name()); \
1462 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001463
Ian Rogers848871b2013-08-05 10:56:33 -07001464 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001465 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001466 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001467 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1468 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001469
Ian Rogers848871b2013-08-05 10:56:33 -07001470 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001471 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001472 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1473 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1474 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001475 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001476 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001477 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001478 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001479 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001480 return offset;
1481}
1482
1483size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001484 #define VISIT(VisitorType) \
1485 do { \
1486 VisitorType visitor(this, offset); \
1487 bool success = VisitDexMethods(&visitor); \
1488 DCHECK(success); \
1489 offset = visitor.GetOffset(); \
1490 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001491
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001492 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001493 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001494 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001495 }
Logan Chien8b977d32012-02-21 19:14:55 +08001496
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001497 #undef VISIT
1498
Brian Carlstrome24fa612011-09-29 00:53:55 -07001499 return offset;
1500}
1501
David Srbeckybc90fd02015-04-22 19:40:27 +01001502bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001503 CHECK(write_state_ == WriteState::kWriteRoData);
1504
1505 if (!WriteClassOffsets(out)) {
1506 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001507 return false;
1508 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001509
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001510 if (!WriteClasses(out)) {
1511 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001512 return false;
1513 }
1514
Vladimir Markof4da6752014-08-01 19:04:18 +01001515 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001516 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001517 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1518 return false;
1519 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001520 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001521 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001522 relative_offset = WriteMaps(out, file_offset, relative_offset);
1523 if (relative_offset == 0) {
1524 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1525 return false;
1526 }
1527
David Srbeckybc90fd02015-04-22 19:40:27 +01001528 // Write padding.
1529 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1530 relative_offset += size_executable_offset_alignment_;
1531 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1532 size_t expected_file_offset = file_offset + relative_offset;
1533 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1534 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1535 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1536 return 0;
1537 }
1538 DCHECK_OFFSET();
1539
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001540 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001541 return true;
1542}
1543
1544bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001545 CHECK(write_state_ == WriteState::kWriteText);
1546
Vladimir Marko944da602016-02-19 12:27:55 +00001547 SetMultiOatRelativePatcherAdjustment();
1548
David Srbeckybc90fd02015-04-22 19:40:27 +01001549 const size_t file_offset = oat_data_offset_;
1550 size_t relative_offset = oat_header_->GetExecutableOffset();
1551 DCHECK_OFFSET();
1552
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001553 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001554 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001555 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001556 return false;
1557 }
1558
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001559 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1560 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001561 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001562 return false;
1563 }
1564
Vladimir Markof4da6752014-08-01 19:04:18 +01001565 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001566 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001567 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1568 return false;
1569 }
1570
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001571 if (kIsDebugBuild) {
1572 uint32_t size_total = 0;
1573 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001574 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001575 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001576
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001577 DO_STAT(size_dex_file_alignment_);
1578 DO_STAT(size_executable_offset_alignment_);
1579 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001580 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001581 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001582 DO_STAT(size_interpreter_to_interpreter_bridge_);
1583 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1584 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001585 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001586 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001587 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001588 DO_STAT(size_quick_to_interpreter_bridge_);
1589 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001590 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001591 DO_STAT(size_code_);
1592 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001593 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001594 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001595 DO_STAT(size_mapping_table_);
1596 DO_STAT(size_vmap_table_);
1597 DO_STAT(size_gc_map_);
1598 DO_STAT(size_oat_dex_file_location_size_);
1599 DO_STAT(size_oat_dex_file_location_data_);
1600 DO_STAT(size_oat_dex_file_location_checksum_);
1601 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001602 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001603 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001604 DO_STAT(size_oat_lookup_table_alignment_);
1605 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001606 DO_STAT(size_oat_class_offsets_alignment_);
1607 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001608 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001609 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001610 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001611 DO_STAT(size_oat_class_method_offsets_);
1612 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001613
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001614 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001615 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001616 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001617 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001618
Vladimir Markof4da6752014-08-01 19:04:18 +01001619 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001620 CHECK_EQ(size_, relative_offset);
1621
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001622 write_state_ = WriteState::kWriteHeader;
1623 return true;
1624}
1625
1626bool OatWriter::WriteHeader(OutputStream* out,
1627 uint32_t image_file_location_oat_checksum,
1628 uintptr_t image_file_location_oat_begin,
1629 int32_t image_patch_delta) {
1630 CHECK(write_state_ == WriteState::kWriteHeader);
1631
1632 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1633 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1634 if (compiler_driver_->IsBootImage()) {
1635 CHECK_EQ(image_patch_delta, 0);
1636 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1637 } else {
1638 CHECK_ALIGNED(image_patch_delta, kPageSize);
1639 oat_header_->SetImagePatchDelta(image_patch_delta);
1640 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001641 oat_header_->UpdateChecksumWithHeaderData();
1642
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001643 const size_t file_offset = oat_data_offset_;
1644
1645 off_t current_offset = out->Seek(0, kSeekCurrent);
1646 if (current_offset == static_cast<off_t>(-1)) {
1647 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1648 return false;
1649 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001650 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001651 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1652 return false;
1653 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001654 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001655
1656 // Flush all other data before writing the header.
1657 if (!out->Flush()) {
1658 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1659 return false;
1660 }
1661 // Write the header.
1662 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001663 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001664 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1665 return false;
1666 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001667 // Flush the header data.
1668 if (!out->Flush()) {
1669 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001670 return false;
1671 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001672
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001673 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1674 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1675 return false;
1676 }
1677 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1678
1679 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001680 return true;
1681}
1682
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001683bool OatWriter::WriteClassOffsets(OutputStream* out) {
1684 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1685 if (oat_dex_file.class_offsets_offset_ != 0u) {
1686 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1687 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1688 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1689 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1690 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001691 return false;
1692 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001693 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1694 return false;
1695 }
1696 }
1697 }
1698 return true;
1699}
1700
1701bool OatWriter::WriteClasses(OutputStream* out) {
1702 for (OatClass& oat_class : oat_classes_) {
1703 if (!oat_class.Write(this, out, oat_data_offset_)) {
1704 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1705 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001706 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001707 }
1708 return true;
1709}
1710
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001711size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1712 #define VISIT(VisitorType) \
1713 do { \
1714 VisitorType visitor(this, out, file_offset, relative_offset); \
1715 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1716 return 0; \
1717 } \
1718 relative_offset = visitor.GetOffset(); \
1719 } while (false)
1720
1721 size_t gc_maps_offset = relative_offset;
1722 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1723 size_gc_map_ = relative_offset - gc_maps_offset;
1724
1725 size_t mapping_tables_offset = relative_offset;
1726 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1727 size_mapping_table_ = relative_offset - mapping_tables_offset;
1728
1729 size_t vmap_tables_offset = relative_offset;
1730 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1731 size_vmap_table_ = relative_offset - vmap_tables_offset;
1732
1733 #undef VISIT
1734
1735 return relative_offset;
1736}
1737
1738size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001739 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001740 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001741
Ian Rogers848871b2013-08-05 10:56:33 -07001742 #define DO_TRAMPOLINE(field) \
1743 do { \
1744 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1745 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001746 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001747 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001748 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001749 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001750 return false; \
1751 } \
1752 size_ ## field += field->size(); \
1753 relative_offset += alignment_padding + field->size(); \
1754 DCHECK_OFFSET(); \
1755 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001756
Ian Rogers848871b2013-08-05 10:56:33 -07001757 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001758 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001759 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001760 DO_TRAMPOLINE(quick_resolution_trampoline_);
1761 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1762 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001763 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001764 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001765}
1766
Ian Rogers3d504072014-03-01 09:16:49 -08001767size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001768 const size_t file_offset,
1769 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001770 #define VISIT(VisitorType) \
1771 do { \
1772 VisitorType visitor(this, out, file_offset, relative_offset); \
1773 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1774 return 0; \
1775 } \
1776 relative_offset = visitor.GetOffset(); \
1777 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001778
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001779 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001780
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001781 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001782
Vladimir Markob163bb72015-03-31 21:49:49 +01001783 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1784 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1785 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1786
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001787 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001788}
1789
Vladimir Marko944da602016-02-19 12:27:55 +00001790bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001791 // Get the elf file offset of the oat file.
1792 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1793 if (raw_file_offset == static_cast<off_t>(-1)) {
1794 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1795 return false;
1796 }
1797 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1798 return true;
1799}
1800
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001801bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1802 // Read the dex file header and perform minimal verification.
1803 uint8_t raw_header[sizeof(DexFile::Header)];
1804 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1805 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1806 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1807 return false;
1808 }
1809 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1810 return false;
1811 }
1812
1813 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1814 oat_dex_file->dex_file_size_ = header->file_size_;
1815 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1816 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1817 return true;
1818}
1819
1820bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1821 if (!DexFile::IsMagicValid(raw_header)) {
1822 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1823 return false;
1824 }
1825 if (!DexFile::IsVersionValid(raw_header)) {
1826 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1827 return false;
1828 }
1829 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1830 if (header->file_size_ < sizeof(DexFile::Header)) {
1831 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1832 << " File: " << location;
1833 return false;
1834 }
1835 return true;
1836}
1837
1838bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1839 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1840
1841 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001842 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001843 return false;
1844 }
1845
1846 // Write dex files.
1847 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1848 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1849 return false;
1850 }
1851 }
1852
1853 // Close sources.
1854 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1855 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1856 }
1857 zipped_dex_files_.clear();
1858 zip_archives_.clear();
1859 raw_dex_files_.clear();
1860 return true;
1861}
1862
1863bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1864 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1865 return false;
1866 }
1867 if (oat_dex_file->source_.IsZipEntry()) {
1868 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1869 return false;
1870 }
1871 } else if (oat_dex_file->source_.IsRawFile()) {
1872 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1873 return false;
1874 }
1875 } else {
1876 DCHECK(oat_dex_file->source_.IsRawData());
1877 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1878 return false;
1879 }
1880 }
1881
1882 // Update current size and account for the written data.
1883 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1884 size_ += oat_dex_file->dex_file_size_;
1885 size_dex_file_ += oat_dex_file->dex_file_size_;
1886 return true;
1887}
1888
1889bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1890 // Dex files are required to be 4 byte aligned.
1891 size_t original_offset = size_;
1892 size_t offset = RoundUp(original_offset, 4);
1893 size_dex_file_alignment_ += offset - original_offset;
1894
1895 // Seek to the start of the dex file and flush any pending operations in the stream.
1896 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1897 uint32_t start_offset = oat_data_offset_ + offset;
1898 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1899 if (actual_offset != static_cast<off_t>(start_offset)) {
1900 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1901 << " Expected: " << start_offset
1902 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1903 return false;
1904 }
1905 if (!out->Flush()) {
1906 PLOG(ERROR) << "Failed to flush before writing dex file."
1907 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1908 return false;
1909 }
1910 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1911 if (actual_offset != static_cast<off_t>(start_offset)) {
1912 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1913 << " Expected: " << start_offset
1914 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1915 return false;
1916 }
1917
1918 size_ = offset;
1919 oat_dex_file->dex_file_offset_ = offset;
1920 return true;
1921}
1922
1923bool OatWriter::WriteDexFile(OutputStream* rodata,
1924 File* file,
1925 OatDexFile* oat_dex_file,
1926 ZipEntry* dex_file) {
1927 size_t start_offset = oat_data_offset_ + size_;
1928 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1929
1930 // Extract the dex file and get the extracted size.
1931 std::string error_msg;
1932 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1933 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1934 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1935 return false;
1936 }
1937 if (file->Flush() != 0) {
1938 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1939 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1940 return false;
1941 }
1942 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1943 if (extracted_end == static_cast<off_t>(-1)) {
1944 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1945 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1946 return false;
1947 }
1948 if (extracted_end < static_cast<off_t>(start_offset)) {
1949 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1950 << " Start: " << start_offset
1951 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1952 return false;
1953 }
1954 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1955 if (extracted_size < sizeof(DexFile::Header)) {
1956 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1957 << extracted_size << " File: " << oat_dex_file->GetLocation();
1958 return false;
1959 }
1960
1961 // Read the dex file header and extract required data to OatDexFile.
1962 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1963 if (actual_offset != static_cast<off_t>(start_offset)) {
1964 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1965 << " Expected: " << start_offset
1966 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1967 return false;
1968 }
1969 if (!ReadDexFileHeader(file, oat_dex_file)) {
1970 return false;
1971 }
1972 if (extracted_size < oat_dex_file->dex_file_size_) {
1973 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1974 << " file size from header: " << oat_dex_file->dex_file_size_
1975 << " File: " << oat_dex_file->GetLocation();
1976 return false;
1977 }
1978
1979 // Override the checksum from header with the CRC from ZIP entry.
1980 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1981
1982 // Seek both file and stream to the end offset.
1983 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1984 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1985 if (actual_offset != static_cast<off_t>(end_offset)) {
1986 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1987 << " Expected: " << end_offset
1988 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1989 return false;
1990 }
1991 actual_offset = rodata->Seek(end_offset, kSeekSet);
1992 if (actual_offset != static_cast<off_t>(end_offset)) {
1993 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1994 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1995 return false;
1996 }
1997 if (!rodata->Flush()) {
1998 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1999 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2000 return false;
2001 }
2002
2003 // If we extracted more than the size specified in the header, truncate the file.
2004 if (extracted_size > oat_dex_file->dex_file_size_) {
2005 if (file->SetLength(end_offset) != 0) {
2006 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2007 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2008 return false;
2009 }
2010 }
2011
2012 return true;
2013}
2014
2015bool OatWriter::WriteDexFile(OutputStream* rodata,
2016 File* file,
2017 OatDexFile* oat_dex_file,
2018 File* dex_file) {
2019 size_t start_offset = oat_data_offset_ + size_;
2020 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2021
2022 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2023 if (input_offset != static_cast<off_t>(0)) {
2024 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2025 << " Expected: 0"
2026 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2027 return false;
2028 }
2029 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2030 return false;
2031 }
2032
2033 // Copy the input dex file using sendfile().
2034 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2035 PLOG(ERROR) << "Failed to copy dex file to oat file."
2036 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2037 return false;
2038 }
2039 if (file->Flush() != 0) {
2040 PLOG(ERROR) << "Failed to flush dex file."
2041 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2042 return false;
2043 }
2044
2045 // Check file position and seek the stream to the end offset.
2046 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2047 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2048 if (actual_offset != static_cast<off_t>(end_offset)) {
2049 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2050 << " Expected: " << end_offset
2051 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2052 return false;
2053 }
2054 actual_offset = rodata->Seek(end_offset, kSeekSet);
2055 if (actual_offset != static_cast<off_t>(end_offset)) {
2056 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2057 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2058 return false;
2059 }
2060 if (!rodata->Flush()) {
2061 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2062 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2063 return false;
2064 }
2065
2066 return true;
2067}
2068
2069bool OatWriter::WriteDexFile(OutputStream* rodata,
2070 OatDexFile* oat_dex_file,
2071 const uint8_t* dex_file) {
2072 // Note: The raw data has already been checked to contain the header
2073 // and all the data that the header specifies as the file size.
2074 DCHECK(dex_file != nullptr);
2075 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2076 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2077
2078 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2079 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2080 << " to " << rodata->GetLocation();
2081 return false;
2082 }
2083 if (!rodata->Flush()) {
2084 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2085 << " File: " << oat_dex_file->GetLocation();
2086 return false;
2087 }
2088
2089 // Update dex file size and resize class offsets in the OatDexFile.
2090 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2091 oat_dex_file->dex_file_size_ = header->file_size_;
2092 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2093 return true;
2094}
2095
2096bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2097 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2098
2099 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2100 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2101 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2102 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2103 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2104 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2105 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2106 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2107 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2108 return false;
2109 }
2110
2111 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2112 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2113
2114 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2115 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2116
2117 // Write OatDexFile.
2118 if (!oat_dex_file->Write(this, rodata)) {
2119 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2120 return false;
2121 }
2122 }
2123
2124 return true;
2125}
2126
2127bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2128 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2129
2130 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2131 if (file->SetLength(new_length) != 0) {
2132 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2133 << "File: " << file->GetPath();
2134 return false;
2135 }
2136 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2137 if (actual_offset != static_cast<off_t>(new_length)) {
2138 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2139 << " Actual: " << actual_offset << " Expected: " << new_length
2140 << " File: " << rodata->GetLocation();
2141 return false;
2142 }
2143 if (!rodata->Flush()) {
2144 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2145 << " File: " << rodata->GetLocation();
2146 return false;
2147 }
2148 return true;
2149}
2150
2151bool OatWriter::OpenDexFiles(
2152 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002153 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002154 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2155 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2156 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2157
2158 if (oat_dex_files_.empty()) {
2159 // Nothing to do.
2160 return true;
2161 }
2162
2163 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2164 size_t length = size_ - map_offset;
2165 std::string error_msg;
2166 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2167 PROT_READ | PROT_WRITE,
2168 MAP_SHARED,
2169 file->Fd(),
2170 oat_data_offset_ + map_offset,
2171 /* low_4gb */ false,
2172 file->GetPath().c_str(),
2173 &error_msg));
2174 if (dex_files_map == nullptr) {
2175 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2176 << " error: " << error_msg;
2177 return false;
2178 }
2179 std::vector<std::unique_ptr<const DexFile>> dex_files;
2180 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2181 // Make sure no one messed with input files while we were copying data.
2182 // At the very least we need consistent file size and number of class definitions.
2183 const uint8_t* raw_dex_file =
2184 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2185 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2186 // Note: ValidateDexFileHeader() already logged an error message.
2187 LOG(ERROR) << "Failed to verify written dex file header!"
2188 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2189 << " ~ " << static_cast<const void*>(raw_dex_file);
2190 return false;
2191 }
2192 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2193 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2194 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2195 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2196 << " Output: " << file->GetPath();
2197 return false;
2198 }
2199 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2200 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2201 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2202 << " Output: " << file->GetPath();
2203 return false;
2204 }
2205
2206 // Now, open the dex file.
2207 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2208 oat_dex_file.dex_file_size_,
2209 oat_dex_file.GetLocation(),
2210 oat_dex_file.dex_file_location_checksum_,
2211 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002212 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002213 &error_msg));
2214 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002215 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2216 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002217 return false;
2218 }
2219 }
2220
2221 *opened_dex_files_map = std::move(dex_files_map);
2222 *opened_dex_files = std::move(dex_files);
2223 return true;
2224}
2225
2226bool OatWriter::WriteTypeLookupTables(
2227 MemMap* opened_dex_files_map,
2228 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2229 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2230
2231 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2232 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2233 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2234 if (oat_dex_file->lookup_table_offset_ != 0u) {
2235 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2236 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2237 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2238 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2239 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2240 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2241 }
2242 }
2243
2244 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2245 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2246 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2247 return false;
2248 }
2249
2250 return true;
2251}
2252
Vladimir Markof4da6752014-08-01 19:04:18 +01002253bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2254 static const uint8_t kPadding[] = {
2255 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2256 };
2257 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2258 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2259 return false;
2260 }
2261 size_code_alignment_ += aligned_code_delta;
2262 return true;
2263}
2264
Vladimir Marko49b0f452015-12-10 13:49:19 +00002265bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2266 oat_header_->UpdateChecksum(data, size);
2267 return out->WriteFully(data, size);
2268}
2269
Vladimir Marko944da602016-02-19 12:27:55 +00002270void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2271 DCHECK(dex_files_ != nullptr);
2272 DCHECK(relative_patcher_ != nullptr);
2273 DCHECK_NE(oat_data_offset_, 0u);
2274 if (image_writer_ != nullptr && !dex_files_->empty()) {
2275 // The oat data begin may not be initialized yet but the oat file offset is ready.
2276 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2277 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2278 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002279 }
2280}
2281
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002282OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2283 DexFileSource source,
2284 CreateTypeLookupTable create_type_lookup_table)
2285 : source_(source),
2286 create_type_lookup_table_(create_type_lookup_table),
2287 dex_file_size_(0),
2288 offset_(0),
2289 dex_file_location_size_(strlen(dex_file_location)),
2290 dex_file_location_data_(dex_file_location),
2291 dex_file_location_checksum_(0u),
2292 dex_file_offset_(0u),
2293 class_offsets_offset_(0u),
2294 lookup_table_offset_(0u),
2295 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002296}
2297
2298size_t OatWriter::OatDexFile::SizeOf() const {
2299 return sizeof(dex_file_location_size_)
2300 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002301 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002302 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002303 + sizeof(class_offsets_offset_)
2304 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002305}
2306
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002307void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2308 DCHECK_EQ(lookup_table_offset_, 0u);
2309 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2310 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2311 if (table_size != 0u) {
2312 // Type tables are required to be 4 byte aligned.
2313 size_t original_offset = oat_writer->size_;
2314 size_t offset = RoundUp(original_offset, 4);
2315 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2316 lookup_table_offset_ = offset;
2317 oat_writer->size_ = offset + table_size;
2318 oat_writer->size_oat_lookup_table_ += table_size;
2319 }
2320 }
2321}
2322
2323void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2324 DCHECK_EQ(class_offsets_offset_, 0u);
2325 if (!class_offsets_.empty()) {
2326 // Class offsets are required to be 4 byte aligned.
2327 size_t original_offset = oat_writer->size_;
2328 size_t offset = RoundUp(original_offset, 4);
2329 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2330 class_offsets_offset_ = offset;
2331 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2332 }
2333}
2334
2335bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2336 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002337 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002338
Vladimir Marko49b0f452015-12-10 13:49:19 +00002339 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002340 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002341 return false;
2342 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002343 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002344
Vladimir Marko49b0f452015-12-10 13:49:19 +00002345 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002346 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002347 return false;
2348 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002349 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002350
Vladimir Marko49b0f452015-12-10 13:49:19 +00002351 if (!oat_writer->WriteData(out,
2352 &dex_file_location_checksum_,
2353 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002354 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002355 return false;
2356 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002357 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002358
Vladimir Marko49b0f452015-12-10 13:49:19 +00002359 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002360 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002361 return false;
2362 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002363 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002364
2365 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2366 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2367 return false;
2368 }
2369 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2370
Vladimir Marko49b0f452015-12-10 13:49:19 +00002371 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002372 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2373 return false;
2374 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002375 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002376
2377 return true;
2378}
2379
2380bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002381 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002382 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2383 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002384 return false;
2385 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002386 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002387 return true;
2388}
2389
Brian Carlstromba150c32013-08-27 17:31:03 -07002390OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002391 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002392 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002393 mirror::Class::Status status)
2394 : compiled_methods_(compiled_methods) {
2395 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002396 CHECK_LE(num_non_null_compiled_methods, num_methods);
2397
Brian Carlstrom265091e2013-01-30 14:08:26 -08002398 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002399 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2400
2401 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2402 // apply when there are 0 methods, we just arbitrarily say that 0
2403 // methods means kOatClassNoneCompiled and that we won't use
2404 // kOatClassAllCompiled unless there is at least one compiled
2405 // method. This means in an interpretter only system, we can assert
2406 // that all classes are kOatClassNoneCompiled.
2407 if (num_non_null_compiled_methods == 0) {
2408 type_ = kOatClassNoneCompiled;
2409 } else if (num_non_null_compiled_methods == num_methods) {
2410 type_ = kOatClassAllCompiled;
2411 } else {
2412 type_ = kOatClassSomeCompiled;
2413 }
2414
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002415 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002416 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002417 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002418
2419 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2420 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002421 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002422 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2423 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2424 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2425 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002426 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002427 method_bitmap_size_ = 0;
2428 }
2429
2430 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002431 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002432 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002433 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2434 } else {
2435 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2436 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2437 if (type_ == kOatClassSomeCompiled) {
2438 method_bitmap_->SetBit(i);
2439 }
2440 }
2441 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002442}
2443
Brian Carlstrom265091e2013-01-30 14:08:26 -08002444size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2445 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002446 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2447 if (method_offset == 0) {
2448 return 0;
2449 }
2450 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002451}
2452
2453size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2454 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002455 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002456}
2457
2458size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002459 return sizeof(status_)
2460 + sizeof(type_)
2461 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2462 + method_bitmap_size_
2463 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002464}
2465
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002466bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002467 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002468 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002469 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002470 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002471 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002472 return false;
2473 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002474 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002475
2476 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002477 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002478 return false;
2479 }
2480 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002481
Brian Carlstromba150c32013-08-27 17:31:03 -07002482 if (method_bitmap_size_ != 0) {
2483 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002484 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002485 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002486 return false;
2487 }
2488 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002489
2490 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002491 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002492 return false;
2493 }
2494 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2495 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002496
2497 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002498 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002499 return false;
2500 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002501 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002502 return true;
2503}
2504
Brian Carlstrome24fa612011-09-29 00:53:55 -07002505} // namespace art