blob: 90ac499ba22243e02ba49d70a7293bc30f616fcc [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"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000033#include "dex/verification_results.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000034#include "driver/compiler_driver.h"
35#include "driver/compiler_options.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000036#include "dwarf/method_debug_info.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 Marko131980f2015-12-03 18:29:23 +000041#include "linker/output_stream.h"
Vladimir Markob163bb72015-03-31 21:49:49 +010042#include "linker/relative_patcher.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),
295 method_offset_map_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000296}
297
298bool OatWriter::AddDexFileSource(const char* filename,
299 const char* location,
300 CreateTypeLookupTable create_type_lookup_table) {
301 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
302 uint32_t magic;
303 std::string error_msg;
304 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
305 if (fd.get() == -1) {
306 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
307 return false;
308 } else if (IsDexMagic(magic)) {
309 // The file is open for reading, not writing, so it's OK to let the File destructor
310 // close it without checking for explicit Close(), so pass checkUsage = false.
311 raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
312 oat_dex_files_.emplace_back(location,
313 DexFileSource(raw_dex_files_.back().get()),
314 create_type_lookup_table);
315 } else if (IsZipMagic(magic)) {
316 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
317 return false;
318 }
319 } else {
320 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
321 return false;
322 }
323 return true;
324}
325
326// Add dex file source(s) from a zip file specified by a file handle.
327bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
328 const char* location,
329 CreateTypeLookupTable create_type_lookup_table) {
330 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
331 std::string error_msg;
332 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
333 ZipArchive* zip_archive = zip_archives_.back().get();
334 if (zip_archive == nullptr) {
335 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
336 << error_msg;
337 return false;
338 }
339 for (size_t i = 0; ; ++i) {
340 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
341 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
342 if (entry == nullptr) {
343 break;
344 }
345 zipped_dex_files_.push_back(std::move(entry));
346 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
347 const char* full_location = zipped_dex_file_locations_.back().c_str();
348 oat_dex_files_.emplace_back(full_location,
349 DexFileSource(zipped_dex_files_.back().get()),
350 create_type_lookup_table);
351 }
352 if (zipped_dex_file_locations_.empty()) {
353 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
354 return false;
355 }
356 return true;
357}
358
359// Add dex file source from raw memory.
360bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
361 const char* location,
362 uint32_t location_checksum,
363 CreateTypeLookupTable create_type_lookup_table) {
364 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
365 if (data.size() < sizeof(DexFile::Header)) {
366 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
367 << data.size() << " File: " << location;
368 return false;
369 }
370 if (!ValidateDexFileHeader(data.data(), location)) {
371 return false;
372 }
373 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
374 if (data.size() < header->file_size_) {
375 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
376 << " file size from header: " << header->file_size_ << " File: " << location;
377 return false;
378 }
379
380 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
381 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
382 return true;
383}
384
385dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
386 dchecked_vector<const char*> locations;
387 locations.reserve(oat_dex_files_.size());
388 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
389 locations.push_back(oat_dex_file.GetLocation());
390 }
391 return locations;
392}
393
394bool OatWriter::WriteAndOpenDexFiles(
395 OutputStream* rodata,
396 File* file,
397 InstructionSet instruction_set,
398 const InstructionSetFeatures* instruction_set_features,
399 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800400 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000401 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
402 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
403 CHECK(write_state_ == WriteState::kAddingDexFileSources);
404
405 size_t offset = InitOatHeader(instruction_set,
406 instruction_set_features,
407 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
408 key_value_store);
409 offset = InitOatDexFiles(offset);
410 size_ = offset;
411
412 std::unique_ptr<MemMap> dex_files_map;
413 std::vector<std::unique_ptr<const DexFile>> dex_files;
414 if (!WriteDexFiles(rodata, file)) {
415 return false;
416 }
417 // Reserve space for type lookup tables and update type_lookup_table_offset_.
418 for (OatDexFile& oat_dex_file : oat_dex_files_) {
419 oat_dex_file.ReserveTypeLookupTable(this);
420 }
421 size_t size_after_type_lookup_tables = size_;
422 // Reserve space for class offsets and update class_offsets_offset_.
423 for (OatDexFile& oat_dex_file : oat_dex_files_) {
424 oat_dex_file.ReserveClassOffsets(this);
425 }
426 if (!WriteOatDexFiles(rodata) ||
427 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800428 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000429 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
430 return false;
431 }
432
433 *opened_dex_files_map = std::move(dex_files_map);
434 *opened_dex_files = std::move(dex_files);
435 write_state_ = WriteState::kPrepareLayout;
436 return true;
437}
438
439void OatWriter::PrepareLayout(const CompilerDriver* compiler,
440 ImageWriter* image_writer,
441 const std::vector<const DexFile*>& dex_files) {
442 CHECK(write_state_ == WriteState::kPrepareLayout);
443
444 dex_files_ = &dex_files;
445
446 compiler_driver_ = compiler;
447 image_writer_ = image_writer;
448 if (compiling_boot_image_) {
449 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800450 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100451 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markob163bb72015-03-31 21:49:49 +0100453 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
454 relative_patcher_ = linker::RelativePatcher::Create(instruction_set, features,
455 &method_offset_map_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100456
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000457 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800458 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000459 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800460 offset = InitOatClasses(offset);
461 }
462 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000463 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100464 offset = InitOatMaps(offset);
465 }
466 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000467 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800468 offset = InitOatCode(offset);
469 }
470 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000471 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800472 offset = InitOatCodeDexFiles(offset);
473 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700474 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700475
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800476 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100477 // Allocate space for app dex cache arrays in the .bss section.
478 size_t bss_start = RoundUp(size_, kPageSize);
479 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
480 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100482 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
483 DexCacheArraysLayout layout(pointer_size, dex_file);
484 bss_size_ += layout.Size();
485 }
486 }
487
Brian Carlstrome24fa612011-09-29 00:53:55 -0700488 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800489 if (compiling_boot_image_) {
490 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000491 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800492 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493
494 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700495}
496
Ian Rogers0571d352011-11-03 19:51:38 -0700497OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700498}
499
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100500struct OatWriter::GcMapDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100501 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100502 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100503 }
504
505 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800506 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
507 return offset == 0u ? 0u :
508 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100509 }
510
511 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
512 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800513 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
514 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100515 }
516
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800517 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100518 return "GC map";
519 }
520};
521
522struct OatWriter::MappingTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100523 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000524 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100525 }
526
527 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100528 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
529 return offset == 0u ? 0u :
530 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100531 }
532
533 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
534 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100535 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
536 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100537 }
538
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800539 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100540 return "mapping table";
541 }
542};
543
544struct OatWriter::VmapTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100545 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800546 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100547 }
548
549 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100550 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
551 return offset == 0u ? 0u :
552 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100553 }
554
555 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
556 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100557 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
558 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100559 }
560
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800561 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100562 return "vmap table";
563 }
564};
565
566class OatWriter::DexMethodVisitor {
567 public:
568 DexMethodVisitor(OatWriter* writer, size_t offset)
569 : writer_(writer),
570 offset_(offset),
571 dex_file_(nullptr),
572 class_def_index_(DexFile::kDexNoIndex) {
573 }
574
575 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
576 DCHECK(dex_file_ == nullptr);
577 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
578 dex_file_ = dex_file;
579 class_def_index_ = class_def_index;
580 return true;
581 }
582
583 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
584
585 virtual bool EndClass() {
586 if (kIsDebugBuild) {
587 dex_file_ = nullptr;
588 class_def_index_ = DexFile::kDexNoIndex;
589 }
590 return true;
591 }
592
593 size_t GetOffset() const {
594 return offset_;
595 }
596
597 protected:
598 virtual ~DexMethodVisitor() { }
599
600 OatWriter* const writer_;
601
602 // The offset is usually advanced for each visited method by the derived class.
603 size_t offset_;
604
605 // The dex file and class def index are set in StartClass().
606 const DexFile* dex_file_;
607 size_t class_def_index_;
608};
609
610class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
611 public:
612 OatDexMethodVisitor(OatWriter* writer, size_t offset)
613 : DexMethodVisitor(writer, offset),
614 oat_class_index_(0u),
615 method_offsets_index_(0u) {
616 }
617
618 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
619 DexMethodVisitor::StartClass(dex_file, class_def_index);
620 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
621 method_offsets_index_ = 0u;
622 return true;
623 }
624
625 bool EndClass() {
626 ++oat_class_index_;
627 return DexMethodVisitor::EndClass();
628 }
629
630 protected:
631 size_t oat_class_index_;
632 size_t method_offsets_index_;
633};
634
635class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
636 public:
637 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
638 : DexMethodVisitor(writer, offset),
639 compiled_methods_(),
640 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000641 size_t num_classes = 0u;
642 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
643 num_classes += oat_dex_file.class_offsets_.size();
644 }
645 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100646 compiled_methods_.reserve(256u);
647 }
648
649 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
650 DexMethodVisitor::StartClass(dex_file, class_def_index);
651 compiled_methods_.clear();
652 num_non_null_compiled_methods_ = 0u;
653 return true;
654 }
655
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300656 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
657 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100658 // Fill in the compiled_methods_ array for methods that have a
659 // CompiledMethod. We track the number of non-null entries in
660 // num_non_null_compiled_methods_ since we only want to allocate
661 // OatMethodOffsets for the compiled methods.
662 uint32_t method_idx = it.GetMemberIndex();
663 CompiledMethod* compiled_method =
664 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
665 compiled_methods_.push_back(compiled_method);
666 if (compiled_method != nullptr) {
667 ++num_non_null_compiled_methods_;
668 }
669 return true;
670 }
671
672 bool EndClass() {
673 ClassReference class_ref(dex_file_, class_def_index_);
674 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
675 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700676 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100677 status = compiled_class->GetStatus();
678 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
679 status = mirror::Class::kStatusError;
680 } else {
681 status = mirror::Class::kStatusNotReady;
682 }
683
Vladimir Marko49b0f452015-12-10 13:49:19 +0000684 writer_->oat_classes_.emplace_back(offset_,
685 compiled_methods_,
686 num_non_null_compiled_methods_,
687 status);
688 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100689 return DexMethodVisitor::EndClass();
690 }
691
692 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000693 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100694 size_t num_non_null_compiled_methods_;
695};
696
697class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
698 public:
699 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100700 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100701 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100702 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100703 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
704 }
705
706 bool EndClass() {
707 OatDexMethodVisitor::EndClass();
708 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100709 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100710 }
711 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100712 }
713
714 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700715 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000716 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100717 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
718
719 if (compiled_method != nullptr) {
720 // Derived from CompiledMethod.
721 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100722
Vladimir Marko35831e82015-09-11 11:59:18 +0100723 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
724 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800725 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800726
David Srbecky009e2a62015-04-15 02:46:30 +0100727 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Markoc74658b2015-03-31 10:26:41 +0100728 bool deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800729 MethodReference method_ref(dex_file_, it.GetMemberIndex());
730 auto method_lb = writer_->method_offset_map_.map.lower_bound(method_ref);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000731 if (debuggable_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800732 if (method_lb != writer_->method_offset_map_.map.end() &&
733 !writer_->method_offset_map_.map.key_comp()(method_ref, method_lb->first)) {
734 // 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.
736 quick_code_offset = method_lb->second;
737 deduped = true;
738 } else {
739 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
740 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000741 } else {
742 auto lb = dedupe_map_.lower_bound(compiled_method);
743 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
744 quick_code_offset = lb->second;
745 deduped = true;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000746 } else {
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000747 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
748 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
David Srbecky009e2a62015-04-15 02:46:30 +0100749 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800750 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100751
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100752 if (code_size != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100753 if (method_lb != writer_->method_offset_map_.map.end() &&
754 !writer_->method_offset_map_.map.key_comp()(method_ref, method_lb->first)) {
755 // TODO: Should this be a hard failure?
756 LOG(WARNING) << "Multiple definitions of "
757 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800758 << " offsets " << method_lb->second << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100759 } else {
760 writer_->method_offset_map_.map.PutBefore(method_lb, method_ref, quick_code_offset);
761 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800762 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100763
Elliott Hughes956af0f2014-12-11 14:34:28 -0800764 // Update quick method header.
765 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
766 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
767 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
768 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100769 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
770 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100771 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800772 uint32_t gc_map_offset = method_header->gc_map_offset_;
773 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
774 // to 0-offset and we need to adjust it by code_offset.
775 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100776 if (mapping_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800777 mapping_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100778 DCHECK_LT(mapping_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800779 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100780 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800781 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100782 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800783 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100784 if (gc_map_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800785 gc_map_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100786 DCHECK_LT(gc_map_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800787 }
788 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
789 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
790 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
791 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
792 gc_map_offset, frame_size_in_bytes, core_spill_mask,
793 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100794
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000795 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800796 // Update offsets. (Checksum is updated when writing.)
797 offset_ += sizeof(*method_header); // Method header is prepended before code.
798 offset_ += code_size;
799 // Record absolute patch locations.
800 if (!compiled_method->GetPatches().empty()) {
801 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
802 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000803 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100804 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100805 }
806 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100807 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800808 }
Alex Light78382fa2014-06-06 15:45:32 -0700809
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000810 if (writer_->compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 // Record debug information for this function if we are doing that.
Elliott Hughes956af0f2014-12-11 14:34:28 -0800812 const uint32_t quick_code_start = quick_code_offset -
David Srbecky6f715892015-03-30 14:21:42 +0100813 writer_->oat_header_->GetExecutableOffset() - thumb_offset;
Vladimir Marko10c13562015-11-25 14:33:36 +0000814 writer_->method_info_.push_back(dwarf::MethodDebugInfo {
David Srbecky0df9e1f2015-04-07 19:02:58 +0100815 dex_file_,
816 class_def_index_,
817 it.GetMemberIndex(),
818 it.GetMethodAccessFlags(),
819 it.GetMethodCodeItem(),
820 deduped,
821 quick_code_start,
822 quick_code_start + code_size,
823 compiled_method});
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100824 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100825
826 if (kIsDebugBuild) {
827 // We expect GC maps except when the class hasn't been verified or the method is native.
828 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
829 ClassReference class_ref(dex_file_, class_def_index_);
830 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
831 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700832 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833 status = compiled_class->GetStatus();
834 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
835 status = mirror::Class::kStatusError;
836 } else {
837 status = mirror::Class::kStatusNotReady;
838 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100839 ArrayRef<const uint8_t> gc_map = compiled_method->GetGcMap();
840 if (!gc_map.empty()) {
841 size_t gc_map_size = gc_map.size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700842 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100843 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
Vladimir Marko35831e82015-09-11 11:59:18 +0100844 << gc_map_size << " " << (is_native ? "true" : "false") << " "
Nicolas Geoffray39468442014-09-02 15:17:15 +0100845 << (status < mirror::Class::kStatusVerified) << " " << status << " "
846 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
847 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100848 }
849
850 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
851 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
852 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100853 ++method_offsets_index_;
854 }
855
856 return true;
857 }
858
859 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000860 struct CodeOffsetsKeyComparator {
861 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100862 // Code is deduplicated by CompilerDriver, compare only data pointers.
863 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
864 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000865 }
866 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100867 if (UNLIKELY(lhs->GetMappingTable().data() != rhs->GetMappingTable().data())) {
868 return lhs->GetMappingTable().data() < rhs->GetMappingTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000869 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100870 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
871 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000872 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100873 if (UNLIKELY(lhs->GetGcMap().data() != rhs->GetGcMap().data())) {
874 return lhs->GetGcMap().data() < rhs->GetGcMap().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000875 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100876 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
877 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000878 }
879 return false;
880 }
881 };
882
David Srbecky009e2a62015-04-15 02:46:30 +0100883 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
884 const ClassDataItemIterator& it,
885 uint32_t thumb_offset) {
886 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100887 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100888 offset_ = compiled_method->AlignCode(offset_);
889 DCHECK_ALIGNED_PARAM(offset_,
890 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
891 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
892 }
893
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100894 // Deduplication is already done on a pointer basis by the compiler driver,
895 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100896 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100897
David Srbecky009e2a62015-04-15 02:46:30 +0100898 // Cache of compiler's --debuggable option.
899 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100900};
901
902template <typename DataAccess>
903class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
904 public:
905 InitMapMethodVisitor(OatWriter* writer, size_t offset)
906 : OatDexMethodVisitor(writer, offset) {
907 }
908
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700909 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700910 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000911 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100912 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
913
914 if (compiled_method != nullptr) {
915 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
916 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
917
Vladimir Marko35831e82015-09-11 11:59:18 +0100918 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
919 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920 if (map_size != 0u) {
Vladimir Marko35831e82015-09-11 11:59:18 +0100921 auto lb = dedupe_map_.lower_bound(map.data());
922 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map.data(), lb->first)) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100923 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100924 } else {
925 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Marko35831e82015-09-11 11:59:18 +0100926 dedupe_map_.PutBefore(lb, map.data(), offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100927 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100928 }
929 }
930 ++method_offsets_index_;
931 }
932
933 return true;
934 }
935
936 private:
937 // Deduplication is already done on a pointer basis by the compiler driver,
938 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100939 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100940};
941
942class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
943 public:
944 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800945 : OatDexMethodVisitor(writer, offset),
946 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100947 }
948
949 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700950 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800951 const DexFile::TypeId& type_id =
952 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
953 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
954 // Skip methods that are not in the image.
955 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
956 return true;
957 }
958
Vladimir Marko49b0f452015-12-10 13:49:19 +0000959 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100960 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
961
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800962 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 if (compiled_method != nullptr) {
964 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
965 offsets = oat_class->method_offsets_[method_offsets_index_];
966 ++method_offsets_index_;
967 }
968
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100970 // Unchecked as we hold mutator_lock_ on entry.
971 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800972 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700973 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
974 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800975 ArtMethod* method;
976 if (writer_->HasBootImage()) {
977 const InvokeType invoke_type = it.GetMethodInvokeType(
978 dex_file_->GetClassDef(class_def_index_));
979 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
980 *dex_file_,
981 it.GetMemberIndex(),
982 dex_cache,
983 ScopedNullHandle<mirror::ClassLoader>(),
984 nullptr,
985 invoke_type);
986 if (method == nullptr) {
987 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
988 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
989 soa.Self()->AssertPendingException();
990 mirror::Throwable* exc = soa.Self()->GetException();
991 std::string dump = exc->Dump();
992 LOG(FATAL) << dump;
993 UNREACHABLE();
994 }
995 } else {
996 // Should already have been resolved by the compiler, just peek into the dex cache.
997 // It may not be resolved if the class failed to verify, in this case, don't set the
998 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
999 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001000 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001001 if (method != nullptr &&
1002 compiled_method != nullptr &&
1003 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001004 method->SetEntryPointFromQuickCompiledCodePtrSize(
1005 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1006 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001007
1008 return true;
1009 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001010
1011 protected:
1012 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001013};
1014
1015class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1016 public:
1017 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001018 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001019 : OatDexMethodVisitor(writer, relative_offset),
1020 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001021 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001022 soa_(Thread::Current()),
1023 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001024 class_linker_(Runtime::Current()->GetClassLinker()),
1025 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001026 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001027 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001028 // If we're creating the image, the address space must be ready so that we can apply patches.
1029 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001030 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001031 }
1032
Vladimir Markof4da6752014-08-01 19:04:18 +01001033 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001034 }
1035
1036 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -07001037 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001038 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1039 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001040 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markof4da6752014-08-01 19:04:18 +01001041 }
1042 return true;
1043 }
1044
Mathieu Chartier90443472015-07-16 20:32:27 -07001045 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001046 bool result = OatDexMethodVisitor::EndClass();
1047 if (oat_class_index_ == writer_->oat_classes_.size()) {
1048 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001049 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001050 if (UNLIKELY(offset_ == 0u)) {
1051 PLOG(ERROR) << "Failed to write final relative call thunks";
1052 result = false;
1053 }
1054 }
1055 return result;
1056 }
1057
1058 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -07001059 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001060 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001061 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1062
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001063 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1064 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001065 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001066 size_t file_offset = file_offset_;
1067 OutputStream* out = out_;
1068
Vladimir Marko35831e82015-09-11 11:59:18 +01001069 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1070 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001071
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001072 // Deduplicate code arrays.
1073 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1074 if (method_offsets.code_offset_ > offset_) {
1075 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1076 if (offset_ == 0u) {
1077 ReportWriteFailure("relative call thunk", it);
1078 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001079 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001080 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1081 uint32_t aligned_code_delta = aligned_offset - offset_;
1082 if (aligned_code_delta != 0) {
1083 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1084 ReportWriteFailure("code alignment padding", it);
1085 return false;
1086 }
1087 offset_ += aligned_code_delta;
1088 DCHECK_OFFSET_();
1089 }
1090 DCHECK_ALIGNED_PARAM(offset_,
1091 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1092 DCHECK_EQ(method_offsets.code_offset_,
1093 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1094 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1095 const OatQuickMethodHeader& method_header =
1096 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +00001097 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001098 ReportWriteFailure("method header", it);
1099 return false;
1100 }
1101 writer_->size_method_header_ += sizeof(method_header);
1102 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001103 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001104
1105 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001106 patched_code_.assign(quick_code.begin(), quick_code.end());
1107 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001108 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1109 if (patch.Type() == kLinkerPatchCallRelative) {
1110 // NOTE: Relative calls across oat files are not supported.
1111 uint32_t target_offset = GetTargetOffset(patch);
1112 uint32_t literal_offset = patch.LiteralOffset();
1113 writer_->relative_patcher_->PatchCall(&patched_code_, literal_offset,
1114 offset_ + literal_offset, target_offset);
1115 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1116 uint32_t target_offset = GetDexCacheOffset(patch);
1117 uint32_t literal_offset = patch.LiteralOffset();
1118 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_, patch,
1119 offset_ + literal_offset,
1120 target_offset);
1121 } else if (patch.Type() == kLinkerPatchCall) {
1122 uint32_t target_offset = GetTargetOffset(patch);
1123 PatchCodeAddress(&patched_code_, patch.LiteralOffset(), target_offset);
1124 } else if (patch.Type() == kLinkerPatchMethod) {
1125 ArtMethod* method = GetTargetMethod(patch);
1126 PatchMethodAddress(&patched_code_, patch.LiteralOffset(), method);
1127 } else if (patch.Type() == kLinkerPatchType) {
1128 mirror::Class* type = GetTargetType(patch);
1129 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), type);
1130 }
1131 }
1132 }
1133
Vladimir Marko49b0f452015-12-10 13:49:19 +00001134 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001135 ReportWriteFailure("method code", it);
1136 return false;
1137 }
1138 writer_->size_code_ += code_size;
1139 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001140 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001141 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001142 ++method_offsets_index_;
1143 }
1144
1145 return true;
1146 }
1147
1148 private:
1149 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001150 const size_t file_offset_;
1151 const ScopedObjectAccess soa_;
1152 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001153 ClassLinker* const class_linker_;
1154 mirror::DexCache* dex_cache_;
1155 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001156
1157 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1158 PLOG(ERROR) << "Failed to write " << what << " for "
1159 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1160 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001161
Mathieu Chartiere401d142015-04-22 13:56:20 -07001162 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001163 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001164 MethodReference ref = patch.TargetMethod();
1165 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001166 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1167 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001168 ArtMethod* method = dex_cache->GetResolvedMethod(
1169 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001170 CHECK(method != nullptr);
1171 return method;
1172 }
1173
Mathieu Chartier90443472015-07-16 20:32:27 -07001174 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markob163bb72015-03-31 21:49:49 +01001175 auto target_it = writer_->method_offset_map_.map.find(patch.TargetMethod());
Vladimir Markof4da6752014-08-01 19:04:18 +01001176 uint32_t target_offset =
Vladimir Markob163bb72015-03-31 21:49:49 +01001177 (target_it != writer_->method_offset_map_.map.end()) ? target_it->second : 0u;
Vladimir Markof4da6752014-08-01 19:04:18 +01001178 // If there's no compiled code, point to the correct trampoline.
1179 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) {
1185 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1186 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1187 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1188 target_offset = PointerToLowMemUInt32(oat_code_offset);
1189 } else {
1190 target_offset = target->IsNative()
1191 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1192 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1193 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001194 }
1195 return target_offset;
1196 }
1197
1198 mirror::Class* GetTargetType(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001199 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001200 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001201 ? dex_cache_ : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001202 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1203 CHECK(type != nullptr);
1204 return type;
1205 }
1206
Mathieu Chartier90443472015-07-16 20:32:27 -07001207 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001208 if (writer_->HasBootImage()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001209 auto* element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<const uint8_t*>(
Vladimir Marko20f85592015-03-19 10:07:02 +00001210 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001211 const char* oat_filename = writer_->image_writer_->GetOatFilenameForDexCache(dex_cache_);
1212 const uint8_t* oat_data =
1213 writer_->image_writer_->GetOatFileBegin(oat_filename) + file_offset_;
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()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001273 const char* oat_filename = writer_->image_writer_->GetOatFilenameForDexCache(dex_cache_);
1274 address = PointerToLowMemUInt32(writer_->image_writer_->GetOatFileBegin(oat_filename) +
Vladimir Marko09d09432015-09-08 13:47:48 +01001275 writer_->oat_data_offset_ + target_offset);
1276 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001277 DCHECK_LE(offset + 4, code->size());
1278 uint8_t* data = &(*code)[offset];
1279 data[0] = address & 0xffu;
1280 data[1] = (address >> 8) & 0xffu;
1281 data[2] = (address >> 16) & 0xffu;
1282 data[3] = (address >> 24) & 0xffu;
1283 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001284};
1285
1286template <typename DataAccess>
1287class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1288 public:
1289 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001290 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001291 : OatDexMethodVisitor(writer, relative_offset),
1292 out_(out),
1293 file_offset_(file_offset) {
1294 }
1295
1296 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001297 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001298 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1299
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001300 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001301 size_t file_offset = file_offset_;
1302 OutputStream* out = out_;
1303
1304 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1305 ++method_offsets_index_;
1306
1307 // Write deduplicated map.
Vladimir Marko35831e82015-09-11 11:59:18 +01001308 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
1309 size_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001310 DCHECK((map_size == 0u && map_offset == 0u) ||
1311 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001312 << map_size << " " << map_offset << " " << offset_ << " "
1313 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001314 if (map_size != 0u && map_offset == offset_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001315 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001316 ReportWriteFailure(it);
1317 return false;
1318 }
1319 offset_ += map_size;
1320 }
1321 DCHECK_OFFSET_();
1322 }
1323
1324 return true;
1325 }
1326
1327 private:
1328 OutputStream* const out_;
1329 size_t const file_offset_;
1330
1331 void ReportWriteFailure(const ClassDataItemIterator& it) {
1332 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1333 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1334 }
1335};
1336
1337// Visit all methods from all classes in all dex files with the specified visitor.
1338bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1339 for (const DexFile* dex_file : *dex_files_) {
1340 const size_t class_def_count = dex_file->NumClassDefs();
1341 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1342 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1343 return false;
1344 }
1345 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001346 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001347 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001348 ClassDataItemIterator it(*dex_file, class_data);
1349 while (it.HasNextStaticField()) {
1350 it.Next();
1351 }
1352 while (it.HasNextInstanceField()) {
1353 it.Next();
1354 }
1355 size_t class_def_method_index = 0u;
1356 while (it.HasNextDirectMethod()) {
1357 if (!visitor->VisitMethod(class_def_method_index, it)) {
1358 return false;
1359 }
1360 ++class_def_method_index;
1361 it.Next();
1362 }
1363 while (it.HasNextVirtualMethod()) {
1364 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1365 return false;
1366 }
1367 ++class_def_method_index;
1368 it.Next();
1369 }
1370 }
1371 if (UNLIKELY(!visitor->EndClass())) {
1372 return false;
1373 }
1374 }
1375 }
1376 return true;
1377}
1378
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001379size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1380 const InstructionSetFeatures* instruction_set_features,
1381 uint32_t num_dex_files,
1382 SafeMap<std::string, std::string>* key_value_store) {
1383 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1384 oat_header_.reset(OatHeader::Create(instruction_set,
1385 instruction_set_features,
1386 num_dex_files,
1387 key_value_store));
1388 size_oat_header_ += sizeof(OatHeader);
1389 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001390 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001391}
1392
1393size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001394 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1395 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001396 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001397 oat_dex_file.offset_ = offset;
1398 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001399 }
1400 return offset;
1401}
1402
Brian Carlstrom389efb02012-01-11 12:06:26 -08001403size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001404 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001405 InitOatClassesMethodVisitor visitor(this, offset);
1406 bool success = VisitDexMethods(&visitor);
1407 CHECK(success);
1408 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001409
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001410 // Update oat_dex_files_.
1411 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001412 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1413 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001414 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001415 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001416 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001417 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001418 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001419 CHECK(oat_class_it == oat_classes_.end());
1420
1421 return offset;
1422}
1423
1424size_t OatWriter::InitOatMaps(size_t offset) {
1425 #define VISIT(VisitorType) \
1426 do { \
1427 VisitorType visitor(this, offset); \
1428 bool success = VisitDexMethods(&visitor); \
1429 DCHECK(success); \
1430 offset = visitor.GetOffset(); \
1431 } while (false)
1432
1433 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1434 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1435 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1436
1437 #undef VISIT
1438
Brian Carlstrome24fa612011-09-29 00:53:55 -07001439 return offset;
1440}
1441
1442size_t OatWriter::InitOatCode(size_t offset) {
1443 // calculate the offsets within OatHeader to executable code
1444 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001445 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001446 // required to be on a new page boundary
1447 offset = RoundUp(offset, kPageSize);
1448 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001449 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001450 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001451 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001452
Ian Rogers848871b2013-08-05 10:56:33 -07001453 #define DO_TRAMPOLINE(field, fn_name) \
1454 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001455 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1456 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001457 field.reset(compiler_driver_->Create ## fn_name()); \
1458 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001459
Ian Rogers848871b2013-08-05 10:56:33 -07001460 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001461 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001462 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001463 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1464 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465
Ian Rogers848871b2013-08-05 10:56:33 -07001466 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001467 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001468 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1469 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1470 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001471 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001472 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001473 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001474 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001475 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001476 return offset;
1477}
1478
1479size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001480 #define VISIT(VisitorType) \
1481 do { \
1482 VisitorType visitor(this, offset); \
1483 bool success = VisitDexMethods(&visitor); \
1484 DCHECK(success); \
1485 offset = visitor.GetOffset(); \
1486 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001487
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001488 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001489 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001490 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001491 }
Logan Chien8b977d32012-02-21 19:14:55 +08001492
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001493 #undef VISIT
1494
Brian Carlstrome24fa612011-09-29 00:53:55 -07001495 return offset;
1496}
1497
David Srbeckybc90fd02015-04-22 19:40:27 +01001498bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001499 CHECK(write_state_ == WriteState::kWriteRoData);
1500
1501 if (!WriteClassOffsets(out)) {
1502 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001503 return false;
1504 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001505
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001506 if (!WriteClasses(out)) {
1507 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001508 return false;
1509 }
1510
Vladimir Markof4da6752014-08-01 19:04:18 +01001511 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001512 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001513 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1514 return false;
1515 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001516 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001517 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001518 relative_offset = WriteMaps(out, file_offset, relative_offset);
1519 if (relative_offset == 0) {
1520 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1521 return false;
1522 }
1523
David Srbeckybc90fd02015-04-22 19:40:27 +01001524 // Write padding.
1525 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1526 relative_offset += size_executable_offset_alignment_;
1527 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1528 size_t expected_file_offset = file_offset + relative_offset;
1529 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1530 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1531 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1532 return 0;
1533 }
1534 DCHECK_OFFSET();
1535
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001536 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001537 return true;
1538}
1539
1540bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001541 CHECK(write_state_ == WriteState::kWriteText);
1542
David Srbeckybc90fd02015-04-22 19:40:27 +01001543 const size_t file_offset = oat_data_offset_;
1544 size_t relative_offset = oat_header_->GetExecutableOffset();
1545 DCHECK_OFFSET();
1546
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001547 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001548 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001549 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001550 return false;
1551 }
1552
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001553 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1554 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001555 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001556 return false;
1557 }
1558
Vladimir Markof4da6752014-08-01 19:04:18 +01001559 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001560 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001561 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1562 return false;
1563 }
1564
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001565 if (kIsDebugBuild) {
1566 uint32_t size_total = 0;
1567 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001568 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001569 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001570
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001571 DO_STAT(size_dex_file_alignment_);
1572 DO_STAT(size_executable_offset_alignment_);
1573 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001574 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001575 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001576 DO_STAT(size_interpreter_to_interpreter_bridge_);
1577 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1578 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001579 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001580 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001581 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001582 DO_STAT(size_quick_to_interpreter_bridge_);
1583 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001584 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001585 DO_STAT(size_code_);
1586 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001587 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001588 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001589 DO_STAT(size_mapping_table_);
1590 DO_STAT(size_vmap_table_);
1591 DO_STAT(size_gc_map_);
1592 DO_STAT(size_oat_dex_file_location_size_);
1593 DO_STAT(size_oat_dex_file_location_data_);
1594 DO_STAT(size_oat_dex_file_location_checksum_);
1595 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001596 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001597 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001598 DO_STAT(size_oat_lookup_table_alignment_);
1599 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001600 DO_STAT(size_oat_class_offsets_alignment_);
1601 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001602 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001603 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001604 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001605 DO_STAT(size_oat_class_method_offsets_);
1606 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001607
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001608 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001609 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001610 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001611 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001612
Vladimir Markof4da6752014-08-01 19:04:18 +01001613 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001614 CHECK_EQ(size_, relative_offset);
1615
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001616 write_state_ = WriteState::kWriteHeader;
1617 return true;
1618}
1619
1620bool OatWriter::WriteHeader(OutputStream* out,
1621 uint32_t image_file_location_oat_checksum,
1622 uintptr_t image_file_location_oat_begin,
1623 int32_t image_patch_delta) {
1624 CHECK(write_state_ == WriteState::kWriteHeader);
1625
1626 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1627 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1628 if (compiler_driver_->IsBootImage()) {
1629 CHECK_EQ(image_patch_delta, 0);
1630 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1631 } else {
1632 CHECK_ALIGNED(image_patch_delta, kPageSize);
1633 oat_header_->SetImagePatchDelta(image_patch_delta);
1634 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001635 oat_header_->UpdateChecksumWithHeaderData();
1636
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001637 const size_t file_offset = oat_data_offset_;
1638
1639 off_t current_offset = out->Seek(0, kSeekCurrent);
1640 if (current_offset == static_cast<off_t>(-1)) {
1641 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1642 return false;
1643 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001644 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001645 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1646 return false;
1647 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001648 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001649
1650 // Flush all other data before writing the header.
1651 if (!out->Flush()) {
1652 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1653 return false;
1654 }
1655 // Write the header.
1656 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001657 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001658 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1659 return false;
1660 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001661 // Flush the header data.
1662 if (!out->Flush()) {
1663 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001664 return false;
1665 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001666
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001667 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1668 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1669 return false;
1670 }
1671 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1672
1673 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001674 return true;
1675}
1676
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001677bool OatWriter::WriteClassOffsets(OutputStream* out) {
1678 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1679 if (oat_dex_file.class_offsets_offset_ != 0u) {
1680 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1681 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1682 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1683 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1684 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001685 return false;
1686 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001687 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1688 return false;
1689 }
1690 }
1691 }
1692 return true;
1693}
1694
1695bool OatWriter::WriteClasses(OutputStream* out) {
1696 for (OatClass& oat_class : oat_classes_) {
1697 if (!oat_class.Write(this, out, oat_data_offset_)) {
1698 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1699 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001700 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001701 }
1702 return true;
1703}
1704
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001705size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1706 #define VISIT(VisitorType) \
1707 do { \
1708 VisitorType visitor(this, out, file_offset, relative_offset); \
1709 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1710 return 0; \
1711 } \
1712 relative_offset = visitor.GetOffset(); \
1713 } while (false)
1714
1715 size_t gc_maps_offset = relative_offset;
1716 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1717 size_gc_map_ = relative_offset - gc_maps_offset;
1718
1719 size_t mapping_tables_offset = relative_offset;
1720 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1721 size_mapping_table_ = relative_offset - mapping_tables_offset;
1722
1723 size_t vmap_tables_offset = relative_offset;
1724 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1725 size_vmap_table_ = relative_offset - vmap_tables_offset;
1726
1727 #undef VISIT
1728
1729 return relative_offset;
1730}
1731
1732size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001733 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001734 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001735
Ian Rogers848871b2013-08-05 10:56:33 -07001736 #define DO_TRAMPOLINE(field) \
1737 do { \
1738 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1739 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001740 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001741 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001742 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001743 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001744 return false; \
1745 } \
1746 size_ ## field += field->size(); \
1747 relative_offset += alignment_padding + field->size(); \
1748 DCHECK_OFFSET(); \
1749 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001750
Ian Rogers848871b2013-08-05 10:56:33 -07001751 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001752 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001753 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001754 DO_TRAMPOLINE(quick_resolution_trampoline_);
1755 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1756 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001757 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001758 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001759}
1760
Ian Rogers3d504072014-03-01 09:16:49 -08001761size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001762 const size_t file_offset,
1763 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001764 #define VISIT(VisitorType) \
1765 do { \
1766 VisitorType visitor(this, out, file_offset, relative_offset); \
1767 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1768 return 0; \
1769 } \
1770 relative_offset = visitor.GetOffset(); \
1771 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001772
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001773 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001774
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001775 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001776
Vladimir Markob163bb72015-03-31 21:49:49 +01001777 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1778 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1779 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1780
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001781 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001782}
1783
Vladimir Marko49b0f452015-12-10 13:49:19 +00001784bool OatWriter::GetOatDataOffset(OutputStream* out) {
1785 // Get the elf file offset of the oat file.
1786 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1787 if (raw_file_offset == static_cast<off_t>(-1)) {
1788 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1789 return false;
1790 }
1791 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1792 return true;
1793}
1794
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001795bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1796 // Read the dex file header and perform minimal verification.
1797 uint8_t raw_header[sizeof(DexFile::Header)];
1798 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1799 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1800 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1801 return false;
1802 }
1803 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1804 return false;
1805 }
1806
1807 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1808 oat_dex_file->dex_file_size_ = header->file_size_;
1809 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1810 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1811 return true;
1812}
1813
1814bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1815 if (!DexFile::IsMagicValid(raw_header)) {
1816 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1817 return false;
1818 }
1819 if (!DexFile::IsVersionValid(raw_header)) {
1820 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1821 return false;
1822 }
1823 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1824 if (header->file_size_ < sizeof(DexFile::Header)) {
1825 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1826 << " File: " << location;
1827 return false;
1828 }
1829 return true;
1830}
1831
1832bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1833 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1834
1835 // Get the elf file offset of the oat file.
1836 if (!GetOatDataOffset(rodata)) {
1837 return false;
1838 }
1839
1840 // Write dex files.
1841 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1842 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1843 return false;
1844 }
1845 }
1846
1847 // Close sources.
1848 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1849 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1850 }
1851 zipped_dex_files_.clear();
1852 zip_archives_.clear();
1853 raw_dex_files_.clear();
1854 return true;
1855}
1856
1857bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1858 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1859 return false;
1860 }
1861 if (oat_dex_file->source_.IsZipEntry()) {
1862 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1863 return false;
1864 }
1865 } else if (oat_dex_file->source_.IsRawFile()) {
1866 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1867 return false;
1868 }
1869 } else {
1870 DCHECK(oat_dex_file->source_.IsRawData());
1871 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1872 return false;
1873 }
1874 }
1875
1876 // Update current size and account for the written data.
1877 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1878 size_ += oat_dex_file->dex_file_size_;
1879 size_dex_file_ += oat_dex_file->dex_file_size_;
1880 return true;
1881}
1882
1883bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1884 // Dex files are required to be 4 byte aligned.
1885 size_t original_offset = size_;
1886 size_t offset = RoundUp(original_offset, 4);
1887 size_dex_file_alignment_ += offset - original_offset;
1888
1889 // Seek to the start of the dex file and flush any pending operations in the stream.
1890 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1891 uint32_t start_offset = oat_data_offset_ + offset;
1892 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1893 if (actual_offset != static_cast<off_t>(start_offset)) {
1894 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1895 << " Expected: " << start_offset
1896 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1897 return false;
1898 }
1899 if (!out->Flush()) {
1900 PLOG(ERROR) << "Failed to flush before writing dex file."
1901 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1902 return false;
1903 }
1904 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1905 if (actual_offset != static_cast<off_t>(start_offset)) {
1906 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1907 << " Expected: " << start_offset
1908 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1909 return false;
1910 }
1911
1912 size_ = offset;
1913 oat_dex_file->dex_file_offset_ = offset;
1914 return true;
1915}
1916
1917bool OatWriter::WriteDexFile(OutputStream* rodata,
1918 File* file,
1919 OatDexFile* oat_dex_file,
1920 ZipEntry* dex_file) {
1921 size_t start_offset = oat_data_offset_ + size_;
1922 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1923
1924 // Extract the dex file and get the extracted size.
1925 std::string error_msg;
1926 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1927 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1928 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1929 return false;
1930 }
1931 if (file->Flush() != 0) {
1932 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1933 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1934 return false;
1935 }
1936 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1937 if (extracted_end == static_cast<off_t>(-1)) {
1938 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1939 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1940 return false;
1941 }
1942 if (extracted_end < static_cast<off_t>(start_offset)) {
1943 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1944 << " Start: " << start_offset
1945 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1946 return false;
1947 }
1948 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1949 if (extracted_size < sizeof(DexFile::Header)) {
1950 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1951 << extracted_size << " File: " << oat_dex_file->GetLocation();
1952 return false;
1953 }
1954
1955 // Read the dex file header and extract required data to OatDexFile.
1956 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1957 if (actual_offset != static_cast<off_t>(start_offset)) {
1958 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1959 << " Expected: " << start_offset
1960 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1961 return false;
1962 }
1963 if (!ReadDexFileHeader(file, oat_dex_file)) {
1964 return false;
1965 }
1966 if (extracted_size < oat_dex_file->dex_file_size_) {
1967 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1968 << " file size from header: " << oat_dex_file->dex_file_size_
1969 << " File: " << oat_dex_file->GetLocation();
1970 return false;
1971 }
1972
1973 // Override the checksum from header with the CRC from ZIP entry.
1974 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1975
1976 // Seek both file and stream to the end offset.
1977 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1978 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1979 if (actual_offset != static_cast<off_t>(end_offset)) {
1980 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1981 << " Expected: " << end_offset
1982 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1983 return false;
1984 }
1985 actual_offset = rodata->Seek(end_offset, kSeekSet);
1986 if (actual_offset != static_cast<off_t>(end_offset)) {
1987 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1988 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1989 return false;
1990 }
1991 if (!rodata->Flush()) {
1992 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1993 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1994 return false;
1995 }
1996
1997 // If we extracted more than the size specified in the header, truncate the file.
1998 if (extracted_size > oat_dex_file->dex_file_size_) {
1999 if (file->SetLength(end_offset) != 0) {
2000 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2001 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2002 return false;
2003 }
2004 }
2005
2006 return true;
2007}
2008
2009bool OatWriter::WriteDexFile(OutputStream* rodata,
2010 File* file,
2011 OatDexFile* oat_dex_file,
2012 File* dex_file) {
2013 size_t start_offset = oat_data_offset_ + size_;
2014 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2015
2016 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2017 if (input_offset != static_cast<off_t>(0)) {
2018 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2019 << " Expected: 0"
2020 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2021 return false;
2022 }
2023 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2024 return false;
2025 }
2026
2027 // Copy the input dex file using sendfile().
2028 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2029 PLOG(ERROR) << "Failed to copy dex file to oat file."
2030 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2031 return false;
2032 }
2033 if (file->Flush() != 0) {
2034 PLOG(ERROR) << "Failed to flush dex file."
2035 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2036 return false;
2037 }
2038
2039 // Check file position and seek the stream to the end offset.
2040 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2041 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2042 if (actual_offset != static_cast<off_t>(end_offset)) {
2043 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2044 << " Expected: " << end_offset
2045 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2046 return false;
2047 }
2048 actual_offset = rodata->Seek(end_offset, kSeekSet);
2049 if (actual_offset != static_cast<off_t>(end_offset)) {
2050 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2051 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2052 return false;
2053 }
2054 if (!rodata->Flush()) {
2055 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2056 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2057 return false;
2058 }
2059
2060 return true;
2061}
2062
2063bool OatWriter::WriteDexFile(OutputStream* rodata,
2064 OatDexFile* oat_dex_file,
2065 const uint8_t* dex_file) {
2066 // Note: The raw data has already been checked to contain the header
2067 // and all the data that the header specifies as the file size.
2068 DCHECK(dex_file != nullptr);
2069 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2070 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2071
2072 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2073 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2074 << " to " << rodata->GetLocation();
2075 return false;
2076 }
2077 if (!rodata->Flush()) {
2078 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2079 << " File: " << oat_dex_file->GetLocation();
2080 return false;
2081 }
2082
2083 // Update dex file size and resize class offsets in the OatDexFile.
2084 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2085 oat_dex_file->dex_file_size_ = header->file_size_;
2086 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2087 return true;
2088}
2089
2090bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2091 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2092
2093 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2094 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2095 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2096 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2097 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2098 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2099 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2100 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2101 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2102 return false;
2103 }
2104
2105 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2106 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2107
2108 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2109 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2110
2111 // Write OatDexFile.
2112 if (!oat_dex_file->Write(this, rodata)) {
2113 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2114 return false;
2115 }
2116 }
2117
2118 return true;
2119}
2120
2121bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2122 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2123
2124 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2125 if (file->SetLength(new_length) != 0) {
2126 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2127 << "File: " << file->GetPath();
2128 return false;
2129 }
2130 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2131 if (actual_offset != static_cast<off_t>(new_length)) {
2132 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2133 << " Actual: " << actual_offset << " Expected: " << new_length
2134 << " File: " << rodata->GetLocation();
2135 return false;
2136 }
2137 if (!rodata->Flush()) {
2138 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2139 << " File: " << rodata->GetLocation();
2140 return false;
2141 }
2142 return true;
2143}
2144
2145bool OatWriter::OpenDexFiles(
2146 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002147 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002148 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2149 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2150 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2151
2152 if (oat_dex_files_.empty()) {
2153 // Nothing to do.
2154 return true;
2155 }
2156
2157 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2158 size_t length = size_ - map_offset;
2159 std::string error_msg;
2160 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2161 PROT_READ | PROT_WRITE,
2162 MAP_SHARED,
2163 file->Fd(),
2164 oat_data_offset_ + map_offset,
2165 /* low_4gb */ false,
2166 file->GetPath().c_str(),
2167 &error_msg));
2168 if (dex_files_map == nullptr) {
2169 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2170 << " error: " << error_msg;
2171 return false;
2172 }
2173 std::vector<std::unique_ptr<const DexFile>> dex_files;
2174 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2175 // Make sure no one messed with input files while we were copying data.
2176 // At the very least we need consistent file size and number of class definitions.
2177 const uint8_t* raw_dex_file =
2178 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2179 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2180 // Note: ValidateDexFileHeader() already logged an error message.
2181 LOG(ERROR) << "Failed to verify written dex file header!"
2182 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2183 << " ~ " << static_cast<const void*>(raw_dex_file);
2184 return false;
2185 }
2186 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2187 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2188 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2189 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2190 << " Output: " << file->GetPath();
2191 return false;
2192 }
2193 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2194 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2195 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2196 << " Output: " << file->GetPath();
2197 return false;
2198 }
2199
2200 // Now, open the dex file.
2201 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2202 oat_dex_file.dex_file_size_,
2203 oat_dex_file.GetLocation(),
2204 oat_dex_file.dex_file_location_checksum_,
2205 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002206 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002207 &error_msg));
2208 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002209 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2210 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002211 return false;
2212 }
2213 }
2214
2215 *opened_dex_files_map = std::move(dex_files_map);
2216 *opened_dex_files = std::move(dex_files);
2217 return true;
2218}
2219
2220bool OatWriter::WriteTypeLookupTables(
2221 MemMap* opened_dex_files_map,
2222 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2223 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2224
2225 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2226 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2227 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2228 if (oat_dex_file->lookup_table_offset_ != 0u) {
2229 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2230 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2231 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2232 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2233 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2234 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2235 }
2236 }
2237
2238 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2239 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2240 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2241 return false;
2242 }
2243
2244 return true;
2245}
2246
Vladimir Markof4da6752014-08-01 19:04:18 +01002247bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2248 static const uint8_t kPadding[] = {
2249 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2250 };
2251 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2252 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2253 return false;
2254 }
2255 size_code_alignment_ += aligned_code_delta;
2256 return true;
2257}
2258
Vladimir Marko49b0f452015-12-10 13:49:19 +00002259bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2260 oat_header_->UpdateChecksum(data, size);
2261 return out->WriteFully(data, size);
2262}
2263
Vladimir Markob163bb72015-03-31 21:49:49 +01002264std::pair<bool, uint32_t> OatWriter::MethodOffsetMap::FindMethodOffset(MethodReference ref) {
2265 auto it = map.find(ref);
2266 if (it == map.end()) {
2267 return std::pair<bool, uint32_t>(false, 0u);
2268 } else {
2269 return std::pair<bool, uint32_t>(true, it->second);
2270 }
2271}
2272
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002273OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2274 DexFileSource source,
2275 CreateTypeLookupTable create_type_lookup_table)
2276 : source_(source),
2277 create_type_lookup_table_(create_type_lookup_table),
2278 dex_file_size_(0),
2279 offset_(0),
2280 dex_file_location_size_(strlen(dex_file_location)),
2281 dex_file_location_data_(dex_file_location),
2282 dex_file_location_checksum_(0u),
2283 dex_file_offset_(0u),
2284 class_offsets_offset_(0u),
2285 lookup_table_offset_(0u),
2286 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002287}
2288
2289size_t OatWriter::OatDexFile::SizeOf() const {
2290 return sizeof(dex_file_location_size_)
2291 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002292 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002293 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002294 + sizeof(class_offsets_offset_)
2295 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002296}
2297
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002298void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2299 DCHECK_EQ(lookup_table_offset_, 0u);
2300 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2301 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2302 if (table_size != 0u) {
2303 // Type tables are required to be 4 byte aligned.
2304 size_t original_offset = oat_writer->size_;
2305 size_t offset = RoundUp(original_offset, 4);
2306 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2307 lookup_table_offset_ = offset;
2308 oat_writer->size_ = offset + table_size;
2309 oat_writer->size_oat_lookup_table_ += table_size;
2310 }
2311 }
2312}
2313
2314void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2315 DCHECK_EQ(class_offsets_offset_, 0u);
2316 if (!class_offsets_.empty()) {
2317 // Class offsets are required to be 4 byte aligned.
2318 size_t original_offset = oat_writer->size_;
2319 size_t offset = RoundUp(original_offset, 4);
2320 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2321 class_offsets_offset_ = offset;
2322 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2323 }
2324}
2325
2326bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2327 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002328 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002329
Vladimir Marko49b0f452015-12-10 13:49:19 +00002330 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002331 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002332 return false;
2333 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002334 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002335
Vladimir Marko49b0f452015-12-10 13:49:19 +00002336 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002337 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002338 return false;
2339 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002340 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002341
Vladimir Marko49b0f452015-12-10 13:49:19 +00002342 if (!oat_writer->WriteData(out,
2343 &dex_file_location_checksum_,
2344 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002345 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002346 return false;
2347 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002348 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002349
Vladimir Marko49b0f452015-12-10 13:49:19 +00002350 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002351 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002352 return false;
2353 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002354 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002355
2356 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2357 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2358 return false;
2359 }
2360 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2361
Vladimir Marko49b0f452015-12-10 13:49:19 +00002362 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002363 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2364 return false;
2365 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002366 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367
2368 return true;
2369}
2370
2371bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002372 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002373 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2374 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002375 return false;
2376 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002377 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002378 return true;
2379}
2380
Brian Carlstromba150c32013-08-27 17:31:03 -07002381OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002382 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002383 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002384 mirror::Class::Status status)
2385 : compiled_methods_(compiled_methods) {
2386 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002387 CHECK_LE(num_non_null_compiled_methods, num_methods);
2388
Brian Carlstrom265091e2013-01-30 14:08:26 -08002389 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002390 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2391
2392 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2393 // apply when there are 0 methods, we just arbitrarily say that 0
2394 // methods means kOatClassNoneCompiled and that we won't use
2395 // kOatClassAllCompiled unless there is at least one compiled
2396 // method. This means in an interpretter only system, we can assert
2397 // that all classes are kOatClassNoneCompiled.
2398 if (num_non_null_compiled_methods == 0) {
2399 type_ = kOatClassNoneCompiled;
2400 } else if (num_non_null_compiled_methods == num_methods) {
2401 type_ = kOatClassAllCompiled;
2402 } else {
2403 type_ = kOatClassSomeCompiled;
2404 }
2405
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002406 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002407 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002408 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002409
2410 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2411 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002412 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002413 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2414 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2415 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2416 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002417 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002418 method_bitmap_size_ = 0;
2419 }
2420
2421 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002422 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002423 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002424 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2425 } else {
2426 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2427 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2428 if (type_ == kOatClassSomeCompiled) {
2429 method_bitmap_->SetBit(i);
2430 }
2431 }
2432 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002433}
2434
Brian Carlstrom265091e2013-01-30 14:08:26 -08002435size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2436 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002437 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2438 if (method_offset == 0) {
2439 return 0;
2440 }
2441 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002442}
2443
2444size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2445 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002446 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002447}
2448
2449size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002450 return sizeof(status_)
2451 + sizeof(type_)
2452 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2453 + method_bitmap_size_
2454 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002455}
2456
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002457bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002458 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002459 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002460 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002461 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002462 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002463 return false;
2464 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002465 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002466
2467 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002468 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002469 return false;
2470 }
2471 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002472
Brian Carlstromba150c32013-08-27 17:31:03 -07002473 if (method_bitmap_size_ != 0) {
2474 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002475 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002476 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002477 return false;
2478 }
2479 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002480
2481 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002482 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002483 return false;
2484 }
2485 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2486 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002487
2488 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002489 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002490 return false;
2491 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002492 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002493 return true;
2494}
2495
Brian Carlstrome24fa612011-09-29 00:53:55 -07002496} // namespace art