blob: a5421622b7f9c847eaf36adff9e9015dd7d4ade0 [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,
400 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
401 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
402 CHECK(write_state_ == WriteState::kAddingDexFileSources);
403
404 size_t offset = InitOatHeader(instruction_set,
405 instruction_set_features,
406 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
407 key_value_store);
408 offset = InitOatDexFiles(offset);
409 size_ = offset;
410
411 std::unique_ptr<MemMap> dex_files_map;
412 std::vector<std::unique_ptr<const DexFile>> dex_files;
413 if (!WriteDexFiles(rodata, file)) {
414 return false;
415 }
416 // Reserve space for type lookup tables and update type_lookup_table_offset_.
417 for (OatDexFile& oat_dex_file : oat_dex_files_) {
418 oat_dex_file.ReserveTypeLookupTable(this);
419 }
420 size_t size_after_type_lookup_tables = size_;
421 // Reserve space for class offsets and update class_offsets_offset_.
422 for (OatDexFile& oat_dex_file : oat_dex_files_) {
423 oat_dex_file.ReserveClassOffsets(this);
424 }
425 if (!WriteOatDexFiles(rodata) ||
426 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
427 !OpenDexFiles(file, &dex_files_map, &dex_files) ||
428 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
429 return false;
430 }
431
432 *opened_dex_files_map = std::move(dex_files_map);
433 *opened_dex_files = std::move(dex_files);
434 write_state_ = WriteState::kPrepareLayout;
435 return true;
436}
437
438void OatWriter::PrepareLayout(const CompilerDriver* compiler,
439 ImageWriter* image_writer,
440 const std::vector<const DexFile*>& dex_files) {
441 CHECK(write_state_ == WriteState::kPrepareLayout);
442
443 dex_files_ = &dex_files;
444
445 compiler_driver_ = compiler;
446 image_writer_ = image_writer;
447 if (compiling_boot_image_) {
448 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800449 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100450 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000451 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markob163bb72015-03-31 21:49:49 +0100452 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
453 relative_patcher_ = linker::RelativePatcher::Create(instruction_set, features,
454 &method_offset_map_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100455
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000456 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800457 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000458 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800459 offset = InitOatClasses(offset);
460 }
461 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000462 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100463 offset = InitOatMaps(offset);
464 }
465 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000466 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800467 offset = InitOatCode(offset);
468 }
469 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000470 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800471 offset = InitOatCodeDexFiles(offset);
472 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700473 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700474
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800475 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100476 // Allocate space for app dex cache arrays in the .bss section.
477 size_t bss_start = RoundUp(size_, kPageSize);
478 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
479 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100481 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
482 DexCacheArraysLayout layout(pointer_size, dex_file);
483 bss_size_ += layout.Size();
484 }
485 }
486
Brian Carlstrome24fa612011-09-29 00:53:55 -0700487 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800488 if (compiling_boot_image_) {
489 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800491 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492
493 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700494}
495
Ian Rogers0571d352011-11-03 19:51:38 -0700496OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700497}
498
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100499struct OatWriter::GcMapDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100500 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100501 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100502 }
503
504 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800505 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
506 return offset == 0u ? 0u :
507 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100508 }
509
510 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
511 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800512 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
513 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100514 }
515
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800516 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100517 return "GC map";
518 }
519};
520
521struct OatWriter::MappingTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100522 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000523 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100524 }
525
526 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100527 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
528 return offset == 0u ? 0u :
529 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100530 }
531
532 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
533 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100534 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
535 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100536 }
537
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800538 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100539 return "mapping table";
540 }
541};
542
543struct OatWriter::VmapTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100544 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800545 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100546 }
547
548 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100549 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
550 return offset == 0u ? 0u :
551 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100552 }
553
554 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
555 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100556 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
557 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100558 }
559
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800560 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100561 return "vmap table";
562 }
563};
564
565class OatWriter::DexMethodVisitor {
566 public:
567 DexMethodVisitor(OatWriter* writer, size_t offset)
568 : writer_(writer),
569 offset_(offset),
570 dex_file_(nullptr),
571 class_def_index_(DexFile::kDexNoIndex) {
572 }
573
574 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
575 DCHECK(dex_file_ == nullptr);
576 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
577 dex_file_ = dex_file;
578 class_def_index_ = class_def_index;
579 return true;
580 }
581
582 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
583
584 virtual bool EndClass() {
585 if (kIsDebugBuild) {
586 dex_file_ = nullptr;
587 class_def_index_ = DexFile::kDexNoIndex;
588 }
589 return true;
590 }
591
592 size_t GetOffset() const {
593 return offset_;
594 }
595
596 protected:
597 virtual ~DexMethodVisitor() { }
598
599 OatWriter* const writer_;
600
601 // The offset is usually advanced for each visited method by the derived class.
602 size_t offset_;
603
604 // The dex file and class def index are set in StartClass().
605 const DexFile* dex_file_;
606 size_t class_def_index_;
607};
608
609class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
610 public:
611 OatDexMethodVisitor(OatWriter* writer, size_t offset)
612 : DexMethodVisitor(writer, offset),
613 oat_class_index_(0u),
614 method_offsets_index_(0u) {
615 }
616
617 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
618 DexMethodVisitor::StartClass(dex_file, class_def_index);
619 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
620 method_offsets_index_ = 0u;
621 return true;
622 }
623
624 bool EndClass() {
625 ++oat_class_index_;
626 return DexMethodVisitor::EndClass();
627 }
628
629 protected:
630 size_t oat_class_index_;
631 size_t method_offsets_index_;
632};
633
634class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
635 public:
636 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
637 : DexMethodVisitor(writer, offset),
638 compiled_methods_(),
639 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000640 size_t num_classes = 0u;
641 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
642 num_classes += oat_dex_file.class_offsets_.size();
643 }
644 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100645 compiled_methods_.reserve(256u);
646 }
647
648 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
649 DexMethodVisitor::StartClass(dex_file, class_def_index);
650 compiled_methods_.clear();
651 num_non_null_compiled_methods_ = 0u;
652 return true;
653 }
654
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300655 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
656 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100657 // Fill in the compiled_methods_ array for methods that have a
658 // CompiledMethod. We track the number of non-null entries in
659 // num_non_null_compiled_methods_ since we only want to allocate
660 // OatMethodOffsets for the compiled methods.
661 uint32_t method_idx = it.GetMemberIndex();
662 CompiledMethod* compiled_method =
663 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
664 compiled_methods_.push_back(compiled_method);
665 if (compiled_method != nullptr) {
666 ++num_non_null_compiled_methods_;
667 }
668 return true;
669 }
670
671 bool EndClass() {
672 ClassReference class_ref(dex_file_, class_def_index_);
673 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
674 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700675 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100676 status = compiled_class->GetStatus();
677 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
678 status = mirror::Class::kStatusError;
679 } else {
680 status = mirror::Class::kStatusNotReady;
681 }
682
Vladimir Marko49b0f452015-12-10 13:49:19 +0000683 writer_->oat_classes_.emplace_back(offset_,
684 compiled_methods_,
685 num_non_null_compiled_methods_,
686 status);
687 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100688 return DexMethodVisitor::EndClass();
689 }
690
691 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000692 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100693 size_t num_non_null_compiled_methods_;
694};
695
696class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
697 public:
698 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100699 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100700 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100701 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100702 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
703 }
704
705 bool EndClass() {
706 OatDexMethodVisitor::EndClass();
707 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100708 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100709 }
710 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100711 }
712
713 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700714 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000715 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100716 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
717
718 if (compiled_method != nullptr) {
719 // Derived from CompiledMethod.
720 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100721
Vladimir Marko35831e82015-09-11 11:59:18 +0100722 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
723 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800724 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800725
David Srbecky009e2a62015-04-15 02:46:30 +0100726 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Markoc74658b2015-03-31 10:26:41 +0100727 bool deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800728 MethodReference method_ref(dex_file_, it.GetMemberIndex());
729 auto method_lb = writer_->method_offset_map_.map.lower_bound(method_ref);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000730 if (debuggable_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800731 if (method_lb != writer_->method_offset_map_.map.end() &&
732 !writer_->method_offset_map_.map.key_comp()(method_ref, method_lb->first)) {
733 // Duplicate methods, we want the same code for both of them so that the oat writer puts
734 // the same code in both ArtMethods so that we do not get different oat code at runtime.
735 quick_code_offset = method_lb->second;
736 deduped = true;
737 } else {
738 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
739 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000740 } else {
741 auto lb = dedupe_map_.lower_bound(compiled_method);
742 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
743 quick_code_offset = lb->second;
744 deduped = true;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000745 } else {
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000746 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
747 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
David Srbecky009e2a62015-04-15 02:46:30 +0100748 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800749 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100750
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100751 if (code_size != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100752 if (method_lb != writer_->method_offset_map_.map.end() &&
753 !writer_->method_offset_map_.map.key_comp()(method_ref, method_lb->first)) {
754 // TODO: Should this be a hard failure?
755 LOG(WARNING) << "Multiple definitions of "
756 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800757 << " offsets " << method_lb->second << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100758 } else {
759 writer_->method_offset_map_.map.PutBefore(method_lb, method_ref, quick_code_offset);
760 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800761 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762
Elliott Hughes956af0f2014-12-11 14:34:28 -0800763 // Update quick method header.
764 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
765 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
766 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
767 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100768 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
769 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100770 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800771 uint32_t gc_map_offset = method_header->gc_map_offset_;
772 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
773 // to 0-offset and we need to adjust it by code_offset.
774 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100775 if (mapping_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800776 mapping_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100777 DCHECK_LT(mapping_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800778 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100779 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800780 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100781 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800782 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100783 if (gc_map_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800784 gc_map_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100785 DCHECK_LT(gc_map_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800786 }
787 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
788 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
789 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
790 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
791 gc_map_offset, frame_size_in_bytes, core_spill_mask,
792 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100793
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000794 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800795 // Update offsets. (Checksum is updated when writing.)
796 offset_ += sizeof(*method_header); // Method header is prepended before code.
797 offset_ += code_size;
798 // Record absolute patch locations.
799 if (!compiled_method->GetPatches().empty()) {
800 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
801 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000802 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100803 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100804 }
805 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 }
Alex Light78382fa2014-06-06 15:45:32 -0700808
David Srbecky8546cc92016-01-25 17:31:49 +0000809 if (writer_->compiler_driver_->GetCompilerOptions().GetGenerateDebugInfo()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800810 // Record debug information for this function if we are doing that.
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 const uint32_t quick_code_start = quick_code_offset -
David Srbecky6f715892015-03-30 14:21:42 +0100812 writer_->oat_header_->GetExecutableOffset() - thumb_offset;
Vladimir Marko10c13562015-11-25 14:33:36 +0000813 writer_->method_info_.push_back(dwarf::MethodDebugInfo {
David Srbecky0df9e1f2015-04-07 19:02:58 +0100814 dex_file_,
815 class_def_index_,
816 it.GetMemberIndex(),
817 it.GetMethodAccessFlags(),
818 it.GetMethodCodeItem(),
819 deduped,
820 quick_code_start,
821 quick_code_start + code_size,
822 compiled_method});
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100823 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100824
825 if (kIsDebugBuild) {
826 // We expect GC maps except when the class hasn't been verified or the method is native.
827 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
828 ClassReference class_ref(dex_file_, class_def_index_);
829 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
830 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700831 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832 status = compiled_class->GetStatus();
833 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
834 status = mirror::Class::kStatusError;
835 } else {
836 status = mirror::Class::kStatusNotReady;
837 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100838 ArrayRef<const uint8_t> gc_map = compiled_method->GetGcMap();
839 if (!gc_map.empty()) {
840 size_t gc_map_size = gc_map.size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700841 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100842 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
Vladimir Marko35831e82015-09-11 11:59:18 +0100843 << gc_map_size << " " << (is_native ? "true" : "false") << " "
Nicolas Geoffray39468442014-09-02 15:17:15 +0100844 << (status < mirror::Class::kStatusVerified) << " " << status << " "
845 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
846 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100847 }
848
849 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
850 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
851 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100852 ++method_offsets_index_;
853 }
854
855 return true;
856 }
857
858 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000859 struct CodeOffsetsKeyComparator {
860 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100861 // Code is deduplicated by CompilerDriver, compare only data pointers.
862 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
863 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000864 }
865 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100866 if (UNLIKELY(lhs->GetMappingTable().data() != rhs->GetMappingTable().data())) {
867 return lhs->GetMappingTable().data() < rhs->GetMappingTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000868 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100869 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
870 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000871 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100872 if (UNLIKELY(lhs->GetGcMap().data() != rhs->GetGcMap().data())) {
873 return lhs->GetGcMap().data() < rhs->GetGcMap().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000874 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100875 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
876 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000877 }
878 return false;
879 }
880 };
881
David Srbecky009e2a62015-04-15 02:46:30 +0100882 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
883 const ClassDataItemIterator& it,
884 uint32_t thumb_offset) {
885 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100886 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100887 offset_ = compiled_method->AlignCode(offset_);
888 DCHECK_ALIGNED_PARAM(offset_,
889 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
890 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
891 }
892
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100893 // Deduplication is already done on a pointer basis by the compiler driver,
894 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100895 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100896
David Srbecky009e2a62015-04-15 02:46:30 +0100897 // Cache of compiler's --debuggable option.
898 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100899};
900
901template <typename DataAccess>
902class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
903 public:
904 InitMapMethodVisitor(OatWriter* writer, size_t offset)
905 : OatDexMethodVisitor(writer, offset) {
906 }
907
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700908 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700909 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000910 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100911 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
912
913 if (compiled_method != nullptr) {
914 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
915 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
916
Vladimir Marko35831e82015-09-11 11:59:18 +0100917 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
918 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100919 if (map_size != 0u) {
Vladimir Marko35831e82015-09-11 11:59:18 +0100920 auto lb = dedupe_map_.lower_bound(map.data());
921 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map.data(), lb->first)) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100922 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923 } else {
924 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Marko35831e82015-09-11 11:59:18 +0100925 dedupe_map_.PutBefore(lb, map.data(), offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100926 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100927 }
928 }
929 ++method_offsets_index_;
930 }
931
932 return true;
933 }
934
935 private:
936 // Deduplication is already done on a pointer basis by the compiler driver,
937 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100938 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939};
940
941class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
942 public:
943 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800944 : OatDexMethodVisitor(writer, offset),
945 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946 }
947
948 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700949 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800950 const DexFile::TypeId& type_id =
951 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
952 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
953 // Skip methods that are not in the image.
954 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
955 return true;
956 }
957
Vladimir Marko49b0f452015-12-10 13:49:19 +0000958 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
960
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800961 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100962 if (compiled_method != nullptr) {
963 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
964 offsets = oat_class->method_offsets_[method_offsets_index_];
965 ++method_offsets_index_;
966 }
967
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100968 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969 // Unchecked as we hold mutator_lock_ on entry.
970 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800971 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700972 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
973 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800974 ArtMethod* method;
975 if (writer_->HasBootImage()) {
976 const InvokeType invoke_type = it.GetMethodInvokeType(
977 dex_file_->GetClassDef(class_def_index_));
978 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
979 *dex_file_,
980 it.GetMemberIndex(),
981 dex_cache,
982 ScopedNullHandle<mirror::ClassLoader>(),
983 nullptr,
984 invoke_type);
985 if (method == nullptr) {
986 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
987 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
988 soa.Self()->AssertPendingException();
989 mirror::Throwable* exc = soa.Self()->GetException();
990 std::string dump = exc->Dump();
991 LOG(FATAL) << dump;
992 UNREACHABLE();
993 }
994 } else {
995 // Should already have been resolved by the compiler, just peek into the dex cache.
996 // It may not be resolved if the class failed to verify, in this case, don't set the
997 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
998 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700999 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001000 if (method != nullptr &&
1001 compiled_method != nullptr &&
1002 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001003 method->SetEntryPointFromQuickCompiledCodePtrSize(
1004 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1005 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001006
1007 return true;
1008 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001009
1010 protected:
1011 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001012};
1013
1014class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1015 public:
1016 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001017 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001018 : OatDexMethodVisitor(writer, relative_offset),
1019 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001020 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001021 soa_(Thread::Current()),
1022 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001023 class_linker_(Runtime::Current()->GetClassLinker()),
1024 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001025 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001026 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001027 // If we're creating the image, the address space must be ready so that we can apply patches.
1028 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001029 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001030 }
1031
Vladimir Markof4da6752014-08-01 19:04:18 +01001032 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001033 }
1034
1035 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -07001036 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001037 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1038 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001039 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markof4da6752014-08-01 19:04:18 +01001040 }
1041 return true;
1042 }
1043
Mathieu Chartier90443472015-07-16 20:32:27 -07001044 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001045 bool result = OatDexMethodVisitor::EndClass();
1046 if (oat_class_index_ == writer_->oat_classes_.size()) {
1047 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001048 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001049 if (UNLIKELY(offset_ == 0u)) {
1050 PLOG(ERROR) << "Failed to write final relative call thunks";
1051 result = false;
1052 }
1053 }
1054 return result;
1055 }
1056
1057 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -07001058 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001059 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001060 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1061
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001062 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1063 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001064 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001065 size_t file_offset = file_offset_;
1066 OutputStream* out = out_;
1067
Vladimir Marko35831e82015-09-11 11:59:18 +01001068 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1069 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001070
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001071 // Deduplicate code arrays.
1072 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1073 if (method_offsets.code_offset_ > offset_) {
1074 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1075 if (offset_ == 0u) {
1076 ReportWriteFailure("relative call thunk", it);
1077 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001078 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001079 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1080 uint32_t aligned_code_delta = aligned_offset - offset_;
1081 if (aligned_code_delta != 0) {
1082 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1083 ReportWriteFailure("code alignment padding", it);
1084 return false;
1085 }
1086 offset_ += aligned_code_delta;
1087 DCHECK_OFFSET_();
1088 }
1089 DCHECK_ALIGNED_PARAM(offset_,
1090 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1091 DCHECK_EQ(method_offsets.code_offset_,
1092 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1093 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1094 const OatQuickMethodHeader& method_header =
1095 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +00001096 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001097 ReportWriteFailure("method header", it);
1098 return false;
1099 }
1100 writer_->size_method_header_ += sizeof(method_header);
1101 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001102 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001103
1104 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001105 patched_code_.assign(quick_code.begin(), quick_code.end());
1106 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001107 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1108 if (patch.Type() == kLinkerPatchCallRelative) {
1109 // NOTE: Relative calls across oat files are not supported.
1110 uint32_t target_offset = GetTargetOffset(patch);
1111 uint32_t literal_offset = patch.LiteralOffset();
1112 writer_->relative_patcher_->PatchCall(&patched_code_, literal_offset,
1113 offset_ + literal_offset, target_offset);
1114 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1115 uint32_t target_offset = GetDexCacheOffset(patch);
1116 uint32_t literal_offset = patch.LiteralOffset();
1117 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_, patch,
1118 offset_ + literal_offset,
1119 target_offset);
1120 } else if (patch.Type() == kLinkerPatchCall) {
1121 uint32_t target_offset = GetTargetOffset(patch);
1122 PatchCodeAddress(&patched_code_, patch.LiteralOffset(), target_offset);
1123 } else if (patch.Type() == kLinkerPatchMethod) {
1124 ArtMethod* method = GetTargetMethod(patch);
1125 PatchMethodAddress(&patched_code_, patch.LiteralOffset(), method);
1126 } else if (patch.Type() == kLinkerPatchType) {
1127 mirror::Class* type = GetTargetType(patch);
1128 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), type);
1129 }
1130 }
1131 }
1132
Vladimir Marko49b0f452015-12-10 13:49:19 +00001133 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001134 ReportWriteFailure("method code", it);
1135 return false;
1136 }
1137 writer_->size_code_ += code_size;
1138 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001139 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001140 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001141 ++method_offsets_index_;
1142 }
1143
1144 return true;
1145 }
1146
1147 private:
1148 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001149 const size_t file_offset_;
1150 const ScopedObjectAccess soa_;
1151 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001152 ClassLinker* const class_linker_;
1153 mirror::DexCache* dex_cache_;
1154 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001155
1156 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1157 PLOG(ERROR) << "Failed to write " << what << " for "
1158 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1159 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001160
Mathieu Chartiere401d142015-04-22 13:56:20 -07001161 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001162 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001163 MethodReference ref = patch.TargetMethod();
1164 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001165 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1166 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001167 ArtMethod* method = dex_cache->GetResolvedMethod(
1168 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001169 CHECK(method != nullptr);
1170 return method;
1171 }
1172
Mathieu Chartier90443472015-07-16 20:32:27 -07001173 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markob163bb72015-03-31 21:49:49 +01001174 auto target_it = writer_->method_offset_map_.map.find(patch.TargetMethod());
Vladimir Markof4da6752014-08-01 19:04:18 +01001175 uint32_t target_offset =
Vladimir Markob163bb72015-03-31 21:49:49 +01001176 (target_it != writer_->method_offset_map_.map.end()) ? target_it->second : 0u;
Vladimir Markof4da6752014-08-01 19:04:18 +01001177 // If there's no compiled code, point to the correct trampoline.
1178 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001179 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001180 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001181 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1182 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1183 if (oat_code_offset != 0) {
1184 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1185 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1186 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1187 target_offset = PointerToLowMemUInt32(oat_code_offset);
1188 } else {
1189 target_offset = target->IsNative()
1190 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1191 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1192 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001193 }
1194 return target_offset;
1195 }
1196
1197 mirror::Class* GetTargetType(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001198 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001199 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001200 ? dex_cache_ : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001201 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1202 CHECK(type != nullptr);
1203 return type;
1204 }
1205
Mathieu Chartier90443472015-07-16 20:32:27 -07001206 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001207 if (writer_->HasBootImage()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001208 auto* element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<const uint8_t*>(
Vladimir Marko20f85592015-03-19 10:07:02 +00001209 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001210 const char* oat_filename = writer_->image_writer_->GetOatFilenameForDexCache(dex_cache_);
1211 const uint8_t* oat_data =
1212 writer_->image_writer_->GetOatFileBegin(oat_filename) + file_offset_;
Vladimir Marko05792b92015-08-03 11:56:49 +01001213 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001214 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001215 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1216 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001217 }
1218 }
1219
Vladimir Markof4da6752014-08-01 19:04:18 +01001220 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001221 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001222 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001223 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001224 } else {
1225 // NOTE: We're using linker patches for app->boot references when the image can
1226 // be relocated and therefore we need to emit .oat_patches. We're not using this
1227 // for app->app references, so check that the object is in the image space.
1228 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001229 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001230 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001231 uint32_t address = PointerToLowMemUInt32(object);
1232 DCHECK_LE(offset + 4, code->size());
1233 uint8_t* data = &(*code)[offset];
1234 data[0] = address & 0xffu;
1235 data[1] = (address >> 8) & 0xffu;
1236 data[2] = (address >> 16) & 0xffu;
1237 data[3] = (address >> 24) & 0xffu;
1238 }
1239
Mathieu Chartiere401d142015-04-22 13:56:20 -07001240 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001241 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001242 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001244 } else if (kIsDebugBuild) {
1245 // NOTE: We're using linker patches for app->boot references when the image can
1246 // be relocated and therefore we need to emit .oat_patches. We're not using this
1247 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001248 std::vector<gc::space::ImageSpace*> image_spaces =
1249 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1250 bool contains_method = false;
1251 for (gc::space::ImageSpace* image_space : image_spaces) {
1252 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1253 contains_method |=
1254 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1255 }
1256 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001257 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001258 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001259 uint32_t address = PointerToLowMemUInt32(method);
1260 DCHECK_LE(offset + 4, code->size());
1261 uint8_t* data = &(*code)[offset];
1262 data[0] = address & 0xffu;
1263 data[1] = (address >> 8) & 0xffu;
1264 data[2] = (address >> 16) & 0xffu;
1265 data[3] = (address >> 24) & 0xffu;
1266 }
1267
Vladimir Markof4da6752014-08-01 19:04:18 +01001268 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001269 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001270 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001271 if (writer_->HasBootImage()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001272 const char* oat_filename = writer_->image_writer_->GetOatFilenameForDexCache(dex_cache_);
1273 address = PointerToLowMemUInt32(writer_->image_writer_->GetOatFileBegin(oat_filename) +
Vladimir Marko09d09432015-09-08 13:47:48 +01001274 writer_->oat_data_offset_ + target_offset);
1275 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001276 DCHECK_LE(offset + 4, code->size());
1277 uint8_t* data = &(*code)[offset];
1278 data[0] = address & 0xffu;
1279 data[1] = (address >> 8) & 0xffu;
1280 data[2] = (address >> 16) & 0xffu;
1281 data[3] = (address >> 24) & 0xffu;
1282 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001283};
1284
1285template <typename DataAccess>
1286class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1287 public:
1288 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001289 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001290 : OatDexMethodVisitor(writer, relative_offset),
1291 out_(out),
1292 file_offset_(file_offset) {
1293 }
1294
1295 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001296 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1298
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001299 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001300 size_t file_offset = file_offset_;
1301 OutputStream* out = out_;
1302
1303 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1304 ++method_offsets_index_;
1305
1306 // Write deduplicated map.
Vladimir Marko35831e82015-09-11 11:59:18 +01001307 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
1308 size_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001309 DCHECK((map_size == 0u && map_offset == 0u) ||
1310 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001311 << map_size << " " << map_offset << " " << offset_ << " "
1312 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001313 if (map_size != 0u && map_offset == offset_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001314 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001315 ReportWriteFailure(it);
1316 return false;
1317 }
1318 offset_ += map_size;
1319 }
1320 DCHECK_OFFSET_();
1321 }
1322
1323 return true;
1324 }
1325
1326 private:
1327 OutputStream* const out_;
1328 size_t const file_offset_;
1329
1330 void ReportWriteFailure(const ClassDataItemIterator& it) {
1331 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1332 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1333 }
1334};
1335
1336// Visit all methods from all classes in all dex files with the specified visitor.
1337bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1338 for (const DexFile* dex_file : *dex_files_) {
1339 const size_t class_def_count = dex_file->NumClassDefs();
1340 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1341 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1342 return false;
1343 }
1344 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001345 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001346 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001347 ClassDataItemIterator it(*dex_file, class_data);
1348 while (it.HasNextStaticField()) {
1349 it.Next();
1350 }
1351 while (it.HasNextInstanceField()) {
1352 it.Next();
1353 }
1354 size_t class_def_method_index = 0u;
1355 while (it.HasNextDirectMethod()) {
1356 if (!visitor->VisitMethod(class_def_method_index, it)) {
1357 return false;
1358 }
1359 ++class_def_method_index;
1360 it.Next();
1361 }
1362 while (it.HasNextVirtualMethod()) {
1363 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1364 return false;
1365 }
1366 ++class_def_method_index;
1367 it.Next();
1368 }
1369 }
1370 if (UNLIKELY(!visitor->EndClass())) {
1371 return false;
1372 }
1373 }
1374 }
1375 return true;
1376}
1377
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001378size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1379 const InstructionSetFeatures* instruction_set_features,
1380 uint32_t num_dex_files,
1381 SafeMap<std::string, std::string>* key_value_store) {
1382 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1383 oat_header_.reset(OatHeader::Create(instruction_set,
1384 instruction_set_features,
1385 num_dex_files,
1386 key_value_store));
1387 size_oat_header_ += sizeof(OatHeader);
1388 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001389 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001390}
1391
1392size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001393 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1394 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001395 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001396 oat_dex_file.offset_ = offset;
1397 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001398 }
1399 return offset;
1400}
1401
Brian Carlstrom389efb02012-01-11 12:06:26 -08001402size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001403 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001404 InitOatClassesMethodVisitor visitor(this, offset);
1405 bool success = VisitDexMethods(&visitor);
1406 CHECK(success);
1407 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001408
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001409 // Update oat_dex_files_.
1410 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001411 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1412 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001413 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001414 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001415 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001416 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001417 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001418 CHECK(oat_class_it == oat_classes_.end());
1419
1420 return offset;
1421}
1422
1423size_t OatWriter::InitOatMaps(size_t offset) {
1424 #define VISIT(VisitorType) \
1425 do { \
1426 VisitorType visitor(this, offset); \
1427 bool success = VisitDexMethods(&visitor); \
1428 DCHECK(success); \
1429 offset = visitor.GetOffset(); \
1430 } while (false)
1431
1432 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1433 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1434 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1435
1436 #undef VISIT
1437
Brian Carlstrome24fa612011-09-29 00:53:55 -07001438 return offset;
1439}
1440
1441size_t OatWriter::InitOatCode(size_t offset) {
1442 // calculate the offsets within OatHeader to executable code
1443 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001444 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001445 // required to be on a new page boundary
1446 offset = RoundUp(offset, kPageSize);
1447 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001448 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001449 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001450 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001451
Ian Rogers848871b2013-08-05 10:56:33 -07001452 #define DO_TRAMPOLINE(field, fn_name) \
1453 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001454 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1455 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001456 field.reset(compiler_driver_->Create ## fn_name()); \
1457 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001458
Ian Rogers848871b2013-08-05 10:56:33 -07001459 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001460 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001461 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001462 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1463 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001464
Ian Rogers848871b2013-08-05 10:56:33 -07001465 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001466 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001467 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1468 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1469 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001470 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001471 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001472 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001473 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001474 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001475 return offset;
1476}
1477
1478size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001479 #define VISIT(VisitorType) \
1480 do { \
1481 VisitorType visitor(this, offset); \
1482 bool success = VisitDexMethods(&visitor); \
1483 DCHECK(success); \
1484 offset = visitor.GetOffset(); \
1485 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001486
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001487 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001488 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001489 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001490 }
Logan Chien8b977d32012-02-21 19:14:55 +08001491
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001492 #undef VISIT
1493
Brian Carlstrome24fa612011-09-29 00:53:55 -07001494 return offset;
1495}
1496
David Srbeckybc90fd02015-04-22 19:40:27 +01001497bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001498 CHECK(write_state_ == WriteState::kWriteRoData);
1499
1500 if (!WriteClassOffsets(out)) {
1501 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001502 return false;
1503 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001504
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001505 if (!WriteClasses(out)) {
1506 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001507 return false;
1508 }
1509
Vladimir Markof4da6752014-08-01 19:04:18 +01001510 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001511 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001512 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1513 return false;
1514 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001515 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001516 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001517 relative_offset = WriteMaps(out, file_offset, relative_offset);
1518 if (relative_offset == 0) {
1519 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1520 return false;
1521 }
1522
David Srbeckybc90fd02015-04-22 19:40:27 +01001523 // Write padding.
1524 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1525 relative_offset += size_executable_offset_alignment_;
1526 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1527 size_t expected_file_offset = file_offset + relative_offset;
1528 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1529 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1530 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1531 return 0;
1532 }
1533 DCHECK_OFFSET();
1534
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001535 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001536 return true;
1537}
1538
1539bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001540 CHECK(write_state_ == WriteState::kWriteText);
1541
David Srbeckybc90fd02015-04-22 19:40:27 +01001542 const size_t file_offset = oat_data_offset_;
1543 size_t relative_offset = oat_header_->GetExecutableOffset();
1544 DCHECK_OFFSET();
1545
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001546 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001547 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001548 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001549 return false;
1550 }
1551
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001552 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1553 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001554 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001555 return false;
1556 }
1557
Vladimir Markof4da6752014-08-01 19:04:18 +01001558 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001559 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001560 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1561 return false;
1562 }
1563
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001564 if (kIsDebugBuild) {
1565 uint32_t size_total = 0;
1566 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001567 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001568 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001569
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001570 DO_STAT(size_dex_file_alignment_);
1571 DO_STAT(size_executable_offset_alignment_);
1572 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001573 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001574 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001575 DO_STAT(size_interpreter_to_interpreter_bridge_);
1576 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1577 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001578 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001579 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001580 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001581 DO_STAT(size_quick_to_interpreter_bridge_);
1582 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001583 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001584 DO_STAT(size_code_);
1585 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001586 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001587 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001588 DO_STAT(size_mapping_table_);
1589 DO_STAT(size_vmap_table_);
1590 DO_STAT(size_gc_map_);
1591 DO_STAT(size_oat_dex_file_location_size_);
1592 DO_STAT(size_oat_dex_file_location_data_);
1593 DO_STAT(size_oat_dex_file_location_checksum_);
1594 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001595 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001596 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001597 DO_STAT(size_oat_lookup_table_alignment_);
1598 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001599 DO_STAT(size_oat_class_offsets_alignment_);
1600 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001601 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001602 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001603 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001604 DO_STAT(size_oat_class_method_offsets_);
1605 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001606
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001607 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001608 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001609 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001610 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001611
Vladimir Markof4da6752014-08-01 19:04:18 +01001612 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001613 CHECK_EQ(size_, relative_offset);
1614
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001615 write_state_ = WriteState::kWriteHeader;
1616 return true;
1617}
1618
1619bool OatWriter::WriteHeader(OutputStream* out,
1620 uint32_t image_file_location_oat_checksum,
1621 uintptr_t image_file_location_oat_begin,
1622 int32_t image_patch_delta) {
1623 CHECK(write_state_ == WriteState::kWriteHeader);
1624
1625 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1626 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1627 if (compiler_driver_->IsBootImage()) {
1628 CHECK_EQ(image_patch_delta, 0);
1629 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1630 } else {
1631 CHECK_ALIGNED(image_patch_delta, kPageSize);
1632 oat_header_->SetImagePatchDelta(image_patch_delta);
1633 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001634 oat_header_->UpdateChecksumWithHeaderData();
1635
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001636 const size_t file_offset = oat_data_offset_;
1637
1638 off_t current_offset = out->Seek(0, kSeekCurrent);
1639 if (current_offset == static_cast<off_t>(-1)) {
1640 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1641 return false;
1642 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001643 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001644 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1645 return false;
1646 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001647 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001648
1649 // Flush all other data before writing the header.
1650 if (!out->Flush()) {
1651 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1652 return false;
1653 }
1654 // Write the header.
1655 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001656 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001657 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1658 return false;
1659 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001660 // Flush the header data.
1661 if (!out->Flush()) {
1662 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001663 return false;
1664 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001665
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001666 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1667 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1668 return false;
1669 }
1670 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1671
1672 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001673 return true;
1674}
1675
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001676bool OatWriter::WriteClassOffsets(OutputStream* out) {
1677 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1678 if (oat_dex_file.class_offsets_offset_ != 0u) {
1679 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1680 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1681 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1682 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1683 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001684 return false;
1685 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001686 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1687 return false;
1688 }
1689 }
1690 }
1691 return true;
1692}
1693
1694bool OatWriter::WriteClasses(OutputStream* out) {
1695 for (OatClass& oat_class : oat_classes_) {
1696 if (!oat_class.Write(this, out, oat_data_offset_)) {
1697 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1698 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001699 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001700 }
1701 return true;
1702}
1703
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001704size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1705 #define VISIT(VisitorType) \
1706 do { \
1707 VisitorType visitor(this, out, file_offset, relative_offset); \
1708 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1709 return 0; \
1710 } \
1711 relative_offset = visitor.GetOffset(); \
1712 } while (false)
1713
1714 size_t gc_maps_offset = relative_offset;
1715 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1716 size_gc_map_ = relative_offset - gc_maps_offset;
1717
1718 size_t mapping_tables_offset = relative_offset;
1719 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1720 size_mapping_table_ = relative_offset - mapping_tables_offset;
1721
1722 size_t vmap_tables_offset = relative_offset;
1723 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1724 size_vmap_table_ = relative_offset - vmap_tables_offset;
1725
1726 #undef VISIT
1727
1728 return relative_offset;
1729}
1730
1731size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001732 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001733 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001734
Ian Rogers848871b2013-08-05 10:56:33 -07001735 #define DO_TRAMPOLINE(field) \
1736 do { \
1737 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1738 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001739 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001740 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001741 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001742 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001743 return false; \
1744 } \
1745 size_ ## field += field->size(); \
1746 relative_offset += alignment_padding + field->size(); \
1747 DCHECK_OFFSET(); \
1748 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001749
Ian Rogers848871b2013-08-05 10:56:33 -07001750 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001751 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001752 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001753 DO_TRAMPOLINE(quick_resolution_trampoline_);
1754 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1755 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001756 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001757 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001758}
1759
Ian Rogers3d504072014-03-01 09:16:49 -08001760size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001761 const size_t file_offset,
1762 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001763 #define VISIT(VisitorType) \
1764 do { \
1765 VisitorType visitor(this, out, file_offset, relative_offset); \
1766 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1767 return 0; \
1768 } \
1769 relative_offset = visitor.GetOffset(); \
1770 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001771
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001772 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001773
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001774 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001775
Vladimir Markob163bb72015-03-31 21:49:49 +01001776 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1777 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1778 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1779
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001780 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001781}
1782
Vladimir Marko49b0f452015-12-10 13:49:19 +00001783bool OatWriter::GetOatDataOffset(OutputStream* out) {
1784 // Get the elf file offset of the oat file.
1785 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1786 if (raw_file_offset == static_cast<off_t>(-1)) {
1787 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1788 return false;
1789 }
1790 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1791 return true;
1792}
1793
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001794bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1795 // Read the dex file header and perform minimal verification.
1796 uint8_t raw_header[sizeof(DexFile::Header)];
1797 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1798 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1799 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1800 return false;
1801 }
1802 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1803 return false;
1804 }
1805
1806 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1807 oat_dex_file->dex_file_size_ = header->file_size_;
1808 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1809 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1810 return true;
1811}
1812
1813bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1814 if (!DexFile::IsMagicValid(raw_header)) {
1815 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1816 return false;
1817 }
1818 if (!DexFile::IsVersionValid(raw_header)) {
1819 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1820 return false;
1821 }
1822 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1823 if (header->file_size_ < sizeof(DexFile::Header)) {
1824 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1825 << " File: " << location;
1826 return false;
1827 }
1828 return true;
1829}
1830
1831bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1832 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1833
1834 // Get the elf file offset of the oat file.
1835 if (!GetOatDataOffset(rodata)) {
1836 return false;
1837 }
1838
1839 // Write dex files.
1840 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1841 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1842 return false;
1843 }
1844 }
1845
1846 // Close sources.
1847 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1848 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1849 }
1850 zipped_dex_files_.clear();
1851 zip_archives_.clear();
1852 raw_dex_files_.clear();
1853 return true;
1854}
1855
1856bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1857 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1858 return false;
1859 }
1860 if (oat_dex_file->source_.IsZipEntry()) {
1861 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1862 return false;
1863 }
1864 } else if (oat_dex_file->source_.IsRawFile()) {
1865 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1866 return false;
1867 }
1868 } else {
1869 DCHECK(oat_dex_file->source_.IsRawData());
1870 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1871 return false;
1872 }
1873 }
1874
1875 // Update current size and account for the written data.
1876 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1877 size_ += oat_dex_file->dex_file_size_;
1878 size_dex_file_ += oat_dex_file->dex_file_size_;
1879 return true;
1880}
1881
1882bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1883 // Dex files are required to be 4 byte aligned.
1884 size_t original_offset = size_;
1885 size_t offset = RoundUp(original_offset, 4);
1886 size_dex_file_alignment_ += offset - original_offset;
1887
1888 // Seek to the start of the dex file and flush any pending operations in the stream.
1889 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1890 uint32_t start_offset = oat_data_offset_ + offset;
1891 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1892 if (actual_offset != static_cast<off_t>(start_offset)) {
1893 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1894 << " Expected: " << start_offset
1895 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1896 return false;
1897 }
1898 if (!out->Flush()) {
1899 PLOG(ERROR) << "Failed to flush before writing dex file."
1900 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1901 return false;
1902 }
1903 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1904 if (actual_offset != static_cast<off_t>(start_offset)) {
1905 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1906 << " Expected: " << start_offset
1907 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1908 return false;
1909 }
1910
1911 size_ = offset;
1912 oat_dex_file->dex_file_offset_ = offset;
1913 return true;
1914}
1915
1916bool OatWriter::WriteDexFile(OutputStream* rodata,
1917 File* file,
1918 OatDexFile* oat_dex_file,
1919 ZipEntry* dex_file) {
1920 size_t start_offset = oat_data_offset_ + size_;
1921 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1922
1923 // Extract the dex file and get the extracted size.
1924 std::string error_msg;
1925 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1926 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1927 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1928 return false;
1929 }
1930 if (file->Flush() != 0) {
1931 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1932 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1933 return false;
1934 }
1935 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1936 if (extracted_end == static_cast<off_t>(-1)) {
1937 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1938 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1939 return false;
1940 }
1941 if (extracted_end < static_cast<off_t>(start_offset)) {
1942 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1943 << " Start: " << start_offset
1944 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1945 return false;
1946 }
1947 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1948 if (extracted_size < sizeof(DexFile::Header)) {
1949 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1950 << extracted_size << " File: " << oat_dex_file->GetLocation();
1951 return false;
1952 }
1953
1954 // Read the dex file header and extract required data to OatDexFile.
1955 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1956 if (actual_offset != static_cast<off_t>(start_offset)) {
1957 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1958 << " Expected: " << start_offset
1959 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1960 return false;
1961 }
1962 if (!ReadDexFileHeader(file, oat_dex_file)) {
1963 return false;
1964 }
1965 if (extracted_size < oat_dex_file->dex_file_size_) {
1966 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1967 << " file size from header: " << oat_dex_file->dex_file_size_
1968 << " File: " << oat_dex_file->GetLocation();
1969 return false;
1970 }
1971
1972 // Override the checksum from header with the CRC from ZIP entry.
1973 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1974
1975 // Seek both file and stream to the end offset.
1976 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1977 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1978 if (actual_offset != static_cast<off_t>(end_offset)) {
1979 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1980 << " Expected: " << end_offset
1981 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1982 return false;
1983 }
1984 actual_offset = rodata->Seek(end_offset, kSeekSet);
1985 if (actual_offset != static_cast<off_t>(end_offset)) {
1986 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1987 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1988 return false;
1989 }
1990 if (!rodata->Flush()) {
1991 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1992 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1993 return false;
1994 }
1995
1996 // If we extracted more than the size specified in the header, truncate the file.
1997 if (extracted_size > oat_dex_file->dex_file_size_) {
1998 if (file->SetLength(end_offset) != 0) {
1999 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2000 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2001 return false;
2002 }
2003 }
2004
2005 return true;
2006}
2007
2008bool OatWriter::WriteDexFile(OutputStream* rodata,
2009 File* file,
2010 OatDexFile* oat_dex_file,
2011 File* dex_file) {
2012 size_t start_offset = oat_data_offset_ + size_;
2013 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2014
2015 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2016 if (input_offset != static_cast<off_t>(0)) {
2017 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2018 << " Expected: 0"
2019 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2020 return false;
2021 }
2022 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2023 return false;
2024 }
2025
2026 // Copy the input dex file using sendfile().
2027 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2028 PLOG(ERROR) << "Failed to copy dex file to oat file."
2029 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2030 return false;
2031 }
2032 if (file->Flush() != 0) {
2033 PLOG(ERROR) << "Failed to flush dex file."
2034 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2035 return false;
2036 }
2037
2038 // Check file position and seek the stream to the end offset.
2039 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2040 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2041 if (actual_offset != static_cast<off_t>(end_offset)) {
2042 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2043 << " Expected: " << end_offset
2044 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2045 return false;
2046 }
2047 actual_offset = rodata->Seek(end_offset, kSeekSet);
2048 if (actual_offset != static_cast<off_t>(end_offset)) {
2049 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2050 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2051 return false;
2052 }
2053 if (!rodata->Flush()) {
2054 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2055 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2056 return false;
2057 }
2058
2059 return true;
2060}
2061
2062bool OatWriter::WriteDexFile(OutputStream* rodata,
2063 OatDexFile* oat_dex_file,
2064 const uint8_t* dex_file) {
2065 // Note: The raw data has already been checked to contain the header
2066 // and all the data that the header specifies as the file size.
2067 DCHECK(dex_file != nullptr);
2068 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2069 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2070
2071 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2072 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2073 << " to " << rodata->GetLocation();
2074 return false;
2075 }
2076 if (!rodata->Flush()) {
2077 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2078 << " File: " << oat_dex_file->GetLocation();
2079 return false;
2080 }
2081
2082 // Update dex file size and resize class offsets in the OatDexFile.
2083 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2084 oat_dex_file->dex_file_size_ = header->file_size_;
2085 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2086 return true;
2087}
2088
2089bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2090 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2091
2092 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2093 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2094 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2095 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2096 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2097 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2098 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2099 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2100 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2101 return false;
2102 }
2103
2104 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2105 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2106
2107 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2108 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2109
2110 // Write OatDexFile.
2111 if (!oat_dex_file->Write(this, rodata)) {
2112 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2113 return false;
2114 }
2115 }
2116
2117 return true;
2118}
2119
2120bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2121 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2122
2123 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2124 if (file->SetLength(new_length) != 0) {
2125 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2126 << "File: " << file->GetPath();
2127 return false;
2128 }
2129 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2130 if (actual_offset != static_cast<off_t>(new_length)) {
2131 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2132 << " Actual: " << actual_offset << " Expected: " << new_length
2133 << " File: " << rodata->GetLocation();
2134 return false;
2135 }
2136 if (!rodata->Flush()) {
2137 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2138 << " File: " << rodata->GetLocation();
2139 return false;
2140 }
2141 return true;
2142}
2143
2144bool OatWriter::OpenDexFiles(
2145 File* file,
2146 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2147 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2148 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2149
2150 if (oat_dex_files_.empty()) {
2151 // Nothing to do.
2152 return true;
2153 }
2154
2155 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2156 size_t length = size_ - map_offset;
2157 std::string error_msg;
2158 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2159 PROT_READ | PROT_WRITE,
2160 MAP_SHARED,
2161 file->Fd(),
2162 oat_data_offset_ + map_offset,
2163 /* low_4gb */ false,
2164 file->GetPath().c_str(),
2165 &error_msg));
2166 if (dex_files_map == nullptr) {
2167 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2168 << " error: " << error_msg;
2169 return false;
2170 }
2171 std::vector<std::unique_ptr<const DexFile>> dex_files;
2172 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2173 // Make sure no one messed with input files while we were copying data.
2174 // At the very least we need consistent file size and number of class definitions.
2175 const uint8_t* raw_dex_file =
2176 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2177 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2178 // Note: ValidateDexFileHeader() already logged an error message.
2179 LOG(ERROR) << "Failed to verify written dex file header!"
2180 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2181 << " ~ " << static_cast<const void*>(raw_dex_file);
2182 return false;
2183 }
2184 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2185 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2186 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2187 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2188 << " Output: " << file->GetPath();
2189 return false;
2190 }
2191 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2192 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2193 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2194 << " Output: " << file->GetPath();
2195 return false;
2196 }
2197
2198 // Now, open the dex file.
2199 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2200 oat_dex_file.dex_file_size_,
2201 oat_dex_file.GetLocation(),
2202 oat_dex_file.dex_file_location_checksum_,
2203 /* oat_dex_file */ nullptr,
2204 &error_msg));
2205 if (dex_files.back() == nullptr) {
2206 LOG(ERROR) << "Failed to open dex file from oat file. File:" << oat_dex_file.GetLocation();
2207 return false;
2208 }
2209 }
2210
2211 *opened_dex_files_map = std::move(dex_files_map);
2212 *opened_dex_files = std::move(dex_files);
2213 return true;
2214}
2215
2216bool OatWriter::WriteTypeLookupTables(
2217 MemMap* opened_dex_files_map,
2218 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2219 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2220
2221 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2222 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2223 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2224 if (oat_dex_file->lookup_table_offset_ != 0u) {
2225 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2226 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2227 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2228 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2229 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2230 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2231 }
2232 }
2233
2234 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2235 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2236 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2237 return false;
2238 }
2239
2240 return true;
2241}
2242
Vladimir Markof4da6752014-08-01 19:04:18 +01002243bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2244 static const uint8_t kPadding[] = {
2245 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2246 };
2247 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2248 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2249 return false;
2250 }
2251 size_code_alignment_ += aligned_code_delta;
2252 return true;
2253}
2254
Vladimir Marko49b0f452015-12-10 13:49:19 +00002255bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2256 oat_header_->UpdateChecksum(data, size);
2257 return out->WriteFully(data, size);
2258}
2259
Vladimir Markob163bb72015-03-31 21:49:49 +01002260std::pair<bool, uint32_t> OatWriter::MethodOffsetMap::FindMethodOffset(MethodReference ref) {
2261 auto it = map.find(ref);
2262 if (it == map.end()) {
2263 return std::pair<bool, uint32_t>(false, 0u);
2264 } else {
2265 return std::pair<bool, uint32_t>(true, it->second);
2266 }
2267}
2268
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002269OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2270 DexFileSource source,
2271 CreateTypeLookupTable create_type_lookup_table)
2272 : source_(source),
2273 create_type_lookup_table_(create_type_lookup_table),
2274 dex_file_size_(0),
2275 offset_(0),
2276 dex_file_location_size_(strlen(dex_file_location)),
2277 dex_file_location_data_(dex_file_location),
2278 dex_file_location_checksum_(0u),
2279 dex_file_offset_(0u),
2280 class_offsets_offset_(0u),
2281 lookup_table_offset_(0u),
2282 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002283}
2284
2285size_t OatWriter::OatDexFile::SizeOf() const {
2286 return sizeof(dex_file_location_size_)
2287 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002288 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002289 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002290 + sizeof(class_offsets_offset_)
2291 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002292}
2293
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002294void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2295 DCHECK_EQ(lookup_table_offset_, 0u);
2296 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2297 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2298 if (table_size != 0u) {
2299 // Type tables are required to be 4 byte aligned.
2300 size_t original_offset = oat_writer->size_;
2301 size_t offset = RoundUp(original_offset, 4);
2302 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2303 lookup_table_offset_ = offset;
2304 oat_writer->size_ = offset + table_size;
2305 oat_writer->size_oat_lookup_table_ += table_size;
2306 }
2307 }
2308}
2309
2310void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2311 DCHECK_EQ(class_offsets_offset_, 0u);
2312 if (!class_offsets_.empty()) {
2313 // Class offsets are required to be 4 byte aligned.
2314 size_t original_offset = oat_writer->size_;
2315 size_t offset = RoundUp(original_offset, 4);
2316 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2317 class_offsets_offset_ = offset;
2318 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2319 }
2320}
2321
2322bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2323 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002324 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002325
Vladimir Marko49b0f452015-12-10 13:49:19 +00002326 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002327 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002328 return false;
2329 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002330 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002331
Vladimir Marko49b0f452015-12-10 13:49:19 +00002332 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002333 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002334 return false;
2335 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002336 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002337
Vladimir Marko49b0f452015-12-10 13:49:19 +00002338 if (!oat_writer->WriteData(out,
2339 &dex_file_location_checksum_,
2340 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002341 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002342 return false;
2343 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002344 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345
Vladimir Marko49b0f452015-12-10 13:49:19 +00002346 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002347 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002348 return false;
2349 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002350 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002351
2352 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2353 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2354 return false;
2355 }
2356 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2357
Vladimir Marko49b0f452015-12-10 13:49:19 +00002358 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002359 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2360 return false;
2361 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002362 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002363
2364 return true;
2365}
2366
2367bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002368 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002369 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2370 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002371 return false;
2372 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002373 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002374 return true;
2375}
2376
Brian Carlstromba150c32013-08-27 17:31:03 -07002377OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002378 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002379 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002380 mirror::Class::Status status)
2381 : compiled_methods_(compiled_methods) {
2382 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002383 CHECK_LE(num_non_null_compiled_methods, num_methods);
2384
Brian Carlstrom265091e2013-01-30 14:08:26 -08002385 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002386 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2387
2388 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2389 // apply when there are 0 methods, we just arbitrarily say that 0
2390 // methods means kOatClassNoneCompiled and that we won't use
2391 // kOatClassAllCompiled unless there is at least one compiled
2392 // method. This means in an interpretter only system, we can assert
2393 // that all classes are kOatClassNoneCompiled.
2394 if (num_non_null_compiled_methods == 0) {
2395 type_ = kOatClassNoneCompiled;
2396 } else if (num_non_null_compiled_methods == num_methods) {
2397 type_ = kOatClassAllCompiled;
2398 } else {
2399 type_ = kOatClassSomeCompiled;
2400 }
2401
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002402 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002403 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002404 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002405
2406 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2407 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002408 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002409 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2410 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2411 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2412 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002413 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002414 method_bitmap_size_ = 0;
2415 }
2416
2417 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002418 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002419 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002420 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2421 } else {
2422 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2423 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2424 if (type_ == kOatClassSomeCompiled) {
2425 method_bitmap_->SetBit(i);
2426 }
2427 }
2428 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002429}
2430
Brian Carlstrom265091e2013-01-30 14:08:26 -08002431size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2432 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002433 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2434 if (method_offset == 0) {
2435 return 0;
2436 }
2437 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002438}
2439
2440size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2441 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002442 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002443}
2444
2445size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002446 return sizeof(status_)
2447 + sizeof(type_)
2448 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2449 + method_bitmap_size_
2450 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002451}
2452
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002453bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002454 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002455 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002456 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002457 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002458 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002459 return false;
2460 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002461 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002462
2463 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002464 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002465 return false;
2466 }
2467 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002468
Brian Carlstromba150c32013-08-27 17:31:03 -07002469 if (method_bitmap_size_ != 0) {
2470 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002471 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002472 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002473 return false;
2474 }
2475 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002476
2477 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002478 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002479 return false;
2480 }
2481 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2482 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002483
2484 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002485 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002486 return false;
2487 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002488 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002489 return true;
2490}
2491
Brian Carlstrome24fa612011-09-29 00:53:55 -07002492} // namespace art