blob: c2f19c9d61604fd7ac7593964c98b465d331f5ac [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000026#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070029#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070030#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000031#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000032#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000033#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "dex_file-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000035#include "driver/compiler_driver.h"
36#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010037#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030039#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010040#include "image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000041#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000042#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/array.h"
44#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010045#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010047#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070048#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070049#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010052#include "utils/dex_cache_arrays_layout-inl.h"
jeffhaoec014232012-09-05 10:42:25 -070053#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000054#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070055
56namespace art {
57
Vladimir Marko9bdf1082016-01-21 12:15:52 +000058namespace { // anonymous namespace
59
60typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
61
62const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
63 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
64}
65
66} // anonymous namespace
67
68// Defines the location of the raw dex file to write.
69class OatWriter::DexFileSource {
70 public:
71 explicit DexFileSource(ZipEntry* zip_entry)
72 : type_(kZipEntry), source_(zip_entry) {
73 DCHECK(source_ != nullptr);
74 }
75
76 explicit DexFileSource(File* raw_file)
77 : type_(kRawFile), source_(raw_file) {
78 DCHECK(source_ != nullptr);
79 }
80
81 explicit DexFileSource(const uint8_t* dex_file)
82 : type_(kRawData), source_(dex_file) {
83 DCHECK(source_ != nullptr);
84 }
85
86 bool IsZipEntry() const { return type_ == kZipEntry; }
87 bool IsRawFile() const { return type_ == kRawFile; }
88 bool IsRawData() const { return type_ == kRawData; }
89
90 ZipEntry* GetZipEntry() const {
91 DCHECK(IsZipEntry());
92 DCHECK(source_ != nullptr);
93 return static_cast<ZipEntry*>(const_cast<void*>(source_));
94 }
95
96 File* GetRawFile() const {
97 DCHECK(IsRawFile());
98 DCHECK(source_ != nullptr);
99 return static_cast<File*>(const_cast<void*>(source_));
100 }
101
102 const uint8_t* GetRawData() const {
103 DCHECK(IsRawData());
104 DCHECK(source_ != nullptr);
105 return static_cast<const uint8_t*>(source_);
106 }
107
108 void Clear() {
109 type_ = kNone;
110 source_ = nullptr;
111 }
112
113 private:
114 enum Type {
115 kNone,
116 kZipEntry,
117 kRawFile,
118 kRawData,
119 };
120
121 Type type_;
122 const void* source_;
123};
124
Vladimir Marko49b0f452015-12-10 13:49:19 +0000125class OatWriter::OatClass {
126 public:
127 OatClass(size_t offset,
128 const dchecked_vector<CompiledMethod*>& compiled_methods,
129 uint32_t num_non_null_compiled_methods,
130 mirror::Class::Status status);
131 OatClass(OatClass&& src) = default;
132 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
133 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
134 size_t SizeOf() const;
135 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
136
137 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
138 return compiled_methods_[class_def_method_index];
139 }
140
141 // Offset of start of OatClass from beginning of OatHeader. It is
142 // used to validate file position when writing.
143 size_t offset_;
144
145 // CompiledMethods for each class_def_method_index, or null if no method is available.
146 dchecked_vector<CompiledMethod*> compiled_methods_;
147
148 // Offset from OatClass::offset_ to the OatMethodOffsets for the
149 // class_def_method_index. If 0, it means the corresponding
150 // CompiledMethod entry in OatClass::compiled_methods_ should be
151 // null and that the OatClass::type_ should be kOatClassBitmap.
152 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
153
154 // Data to write.
155
156 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
157 int16_t status_;
158
159 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
160 uint16_t type_;
161
162 uint32_t method_bitmap_size_;
163
164 // bit vector indexed by ClassDef method index. When
165 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
166 // method has an OatMethodOffsets in methods_offsets_, otherwise
167 // the entry was ommited to save space. If OatClassType::type_ is
168 // not is kOatClassBitmap, the bitmap will be null.
169 std::unique_ptr<BitVector> method_bitmap_;
170
171 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
172 // present in the OatClass. Note that some may be missing if
173 // OatClass::compiled_methods_ contains null values (and
174 // oat_method_offsets_offsets_from_oat_class_ should contain 0
175 // values in this case).
176 dchecked_vector<OatMethodOffsets> method_offsets_;
177 dchecked_vector<OatQuickMethodHeader> method_headers_;
178
179 private:
180 size_t GetMethodOffsetsRawSize() const {
181 return method_offsets_.size() * sizeof(method_offsets_[0]);
182 }
183
184 DISALLOW_COPY_AND_ASSIGN(OatClass);
185};
186
187class OatWriter::OatDexFile {
188 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000189 OatDexFile(const char* dex_file_location,
190 DexFileSource source,
191 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000192 OatDexFile(OatDexFile&& src) = default;
193
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000194 const char* GetLocation() const {
195 return dex_file_location_data_;
196 }
197
198 void ReserveTypeLookupTable(OatWriter* oat_writer);
199 void ReserveClassOffsets(OatWriter* oat_writer);
200
Vladimir Marko49b0f452015-12-10 13:49:19 +0000201 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000202 bool Write(OatWriter* oat_writer, OutputStream* out) const;
203 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
204
205 // The source of the dex file.
206 DexFileSource source_;
207
208 // Whether to create the type lookup table.
209 CreateTypeLookupTable create_type_lookup_table_;
210
211 // Dex file size. Initialized when writing the dex file.
212 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000213
214 // Offset of start of OatDexFile from beginning of OatHeader. It is
215 // used to validate file position when writing.
216 size_t offset_;
217
218 // Data to write.
219 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000220 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000221 uint32_t dex_file_location_checksum_;
222 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000223 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000224 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225
226 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000227 dchecked_vector<uint32_t> class_offsets_;
228
229 private:
230 size_t GetClassOffsetsRawSize() const {
231 return class_offsets_.size() * sizeof(class_offsets_[0]);
232 }
233
234 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
235};
236
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100237#define DCHECK_OFFSET() \
238 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
239 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
240
241#define DCHECK_OFFSET_() \
242 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
243 << "file_offset=" << file_offset << " offset_=" << offset_
244
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000245OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
246 : write_state_(WriteState::kAddingDexFileSources),
247 timings_(timings),
248 raw_dex_files_(),
249 zip_archives_(),
250 zipped_dex_files_(),
251 zipped_dex_file_locations_(),
252 compiler_driver_(nullptr),
253 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800254 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100256 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000257 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100258 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700259 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700260 size_dex_file_alignment_(0),
261 size_executable_offset_alignment_(0),
262 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700263 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700264 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700265 size_interpreter_to_interpreter_bridge_(0),
266 size_interpreter_to_compiled_code_bridge_(0),
267 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800268 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700269 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700270 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700271 size_quick_to_interpreter_bridge_(0),
272 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100273 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700274 size_code_(0),
275 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100276 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100277 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700278 size_mapping_table_(0),
279 size_vmap_table_(0),
280 size_gc_map_(0),
281 size_oat_dex_file_location_size_(0),
282 size_oat_dex_file_location_data_(0),
283 size_oat_dex_file_location_checksum_(0),
284 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000285 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000286 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000287 size_oat_lookup_table_alignment_(0),
288 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000289 size_oat_class_offsets_alignment_(0),
290 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700291 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700292 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700293 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100294 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000295 relative_patcher_(nullptr),
296 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000297}
298
299bool OatWriter::AddDexFileSource(const char* filename,
300 const char* location,
301 CreateTypeLookupTable create_type_lookup_table) {
302 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
303 uint32_t magic;
304 std::string error_msg;
305 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
306 if (fd.get() == -1) {
307 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
308 return false;
309 } else if (IsDexMagic(magic)) {
310 // The file is open for reading, not writing, so it's OK to let the File destructor
311 // close it without checking for explicit Close(), so pass checkUsage = false.
312 raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
313 oat_dex_files_.emplace_back(location,
314 DexFileSource(raw_dex_files_.back().get()),
315 create_type_lookup_table);
316 } else if (IsZipMagic(magic)) {
317 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
318 return false;
319 }
320 } else {
321 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
322 return false;
323 }
324 return true;
325}
326
327// Add dex file source(s) from a zip file specified by a file handle.
328bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
329 const char* location,
330 CreateTypeLookupTable create_type_lookup_table) {
331 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
332 std::string error_msg;
333 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
334 ZipArchive* zip_archive = zip_archives_.back().get();
335 if (zip_archive == nullptr) {
336 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
337 << error_msg;
338 return false;
339 }
340 for (size_t i = 0; ; ++i) {
341 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
342 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
343 if (entry == nullptr) {
344 break;
345 }
346 zipped_dex_files_.push_back(std::move(entry));
347 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
348 const char* full_location = zipped_dex_file_locations_.back().c_str();
349 oat_dex_files_.emplace_back(full_location,
350 DexFileSource(zipped_dex_files_.back().get()),
351 create_type_lookup_table);
352 }
353 if (zipped_dex_file_locations_.empty()) {
354 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
355 return false;
356 }
357 return true;
358}
359
360// Add dex file source from raw memory.
361bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
362 const char* location,
363 uint32_t location_checksum,
364 CreateTypeLookupTable create_type_lookup_table) {
365 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
366 if (data.size() < sizeof(DexFile::Header)) {
367 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
368 << data.size() << " File: " << location;
369 return false;
370 }
371 if (!ValidateDexFileHeader(data.data(), location)) {
372 return false;
373 }
374 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
375 if (data.size() < header->file_size_) {
376 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
377 << " file size from header: " << header->file_size_ << " File: " << location;
378 return false;
379 }
380
381 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
382 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
383 return true;
384}
385
386dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
387 dchecked_vector<const char*> locations;
388 locations.reserve(oat_dex_files_.size());
389 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
390 locations.push_back(oat_dex_file.GetLocation());
391 }
392 return locations;
393}
394
395bool OatWriter::WriteAndOpenDexFiles(
396 OutputStream* rodata,
397 File* file,
398 InstructionSet instruction_set,
399 const InstructionSetFeatures* instruction_set_features,
400 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800401 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000402 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
403 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
404 CHECK(write_state_ == WriteState::kAddingDexFileSources);
405
406 size_t offset = InitOatHeader(instruction_set,
407 instruction_set_features,
408 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
409 key_value_store);
410 offset = InitOatDexFiles(offset);
411 size_ = offset;
412
413 std::unique_ptr<MemMap> dex_files_map;
414 std::vector<std::unique_ptr<const DexFile>> dex_files;
415 if (!WriteDexFiles(rodata, file)) {
416 return false;
417 }
418 // Reserve space for type lookup tables and update type_lookup_table_offset_.
419 for (OatDexFile& oat_dex_file : oat_dex_files_) {
420 oat_dex_file.ReserveTypeLookupTable(this);
421 }
422 size_t size_after_type_lookup_tables = size_;
423 // Reserve space for class offsets and update class_offsets_offset_.
424 for (OatDexFile& oat_dex_file : oat_dex_files_) {
425 oat_dex_file.ReserveClassOffsets(this);
426 }
427 if (!WriteOatDexFiles(rodata) ||
428 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800429 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000430 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
431 return false;
432 }
433
434 *opened_dex_files_map = std::move(dex_files_map);
435 *opened_dex_files = std::move(dex_files);
436 write_state_ = WriteState::kPrepareLayout;
437 return true;
438}
439
440void OatWriter::PrepareLayout(const CompilerDriver* compiler,
441 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000442 const std::vector<const DexFile*>& dex_files,
443 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 CHECK(write_state_ == WriteState::kPrepareLayout);
445
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000446 compiler_driver_ = compiler;
447 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000448 dex_files_ = &dex_files;
449 relative_patcher_ = relative_patcher;
450 SetMultiOatRelativePatcherAdjustment();
451
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 if (compiling_boot_image_) {
453 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800454 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100455 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000456 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100457
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000458 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800459 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000460 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800461 offset = InitOatClasses(offset);
462 }
463 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000464 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100465 offset = InitOatMaps(offset);
466 }
467 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000468 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800469 offset = InitOatCode(offset);
470 }
471 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000472 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800473 offset = InitOatCodeDexFiles(offset);
474 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700475 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700476
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800477 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100478 // Allocate space for app dex cache arrays in the .bss section.
479 size_t bss_start = RoundUp(size_, kPageSize);
480 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
481 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000482 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100483 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
484 DexCacheArraysLayout layout(pointer_size, dex_file);
485 bss_size_ += layout.Size();
486 }
487 }
488
Brian Carlstrome24fa612011-09-29 00:53:55 -0700489 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800490 if (compiling_boot_image_) {
491 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800493 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000494
495 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700496}
497
Ian Rogers0571d352011-11-03 19:51:38 -0700498OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700499}
500
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100501struct OatWriter::GcMapDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100502 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100503 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100504 }
505
506 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800507 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
508 return offset == 0u ? 0u :
509 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100510 }
511
512 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
513 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800514 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
515 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100516 }
517
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800518 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100519 return "GC map";
520 }
521};
522
523struct OatWriter::MappingTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100524 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000525 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100526 }
527
528 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100529 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
530 return offset == 0u ? 0u :
531 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100532 }
533
534 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
535 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100536 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
537 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100538 }
539
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800540 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100541 return "mapping table";
542 }
543};
544
545struct OatWriter::VmapTableDataAccess {
Vladimir Marko35831e82015-09-11 11:59:18 +0100546 static ArrayRef<const uint8_t> GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800547 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100548 }
549
550 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100551 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
552 return offset == 0u ? 0u :
553 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100554 }
555
556 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
557 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100558 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
559 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100560 }
561
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800562 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100563 return "vmap table";
564 }
565};
566
567class OatWriter::DexMethodVisitor {
568 public:
569 DexMethodVisitor(OatWriter* writer, size_t offset)
570 : writer_(writer),
571 offset_(offset),
572 dex_file_(nullptr),
573 class_def_index_(DexFile::kDexNoIndex) {
574 }
575
576 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
577 DCHECK(dex_file_ == nullptr);
578 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
579 dex_file_ = dex_file;
580 class_def_index_ = class_def_index;
581 return true;
582 }
583
584 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
585
586 virtual bool EndClass() {
587 if (kIsDebugBuild) {
588 dex_file_ = nullptr;
589 class_def_index_ = DexFile::kDexNoIndex;
590 }
591 return true;
592 }
593
594 size_t GetOffset() const {
595 return offset_;
596 }
597
598 protected:
599 virtual ~DexMethodVisitor() { }
600
601 OatWriter* const writer_;
602
603 // The offset is usually advanced for each visited method by the derived class.
604 size_t offset_;
605
606 // The dex file and class def index are set in StartClass().
607 const DexFile* dex_file_;
608 size_t class_def_index_;
609};
610
611class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
612 public:
613 OatDexMethodVisitor(OatWriter* writer, size_t offset)
614 : DexMethodVisitor(writer, offset),
615 oat_class_index_(0u),
616 method_offsets_index_(0u) {
617 }
618
619 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
620 DexMethodVisitor::StartClass(dex_file, class_def_index);
621 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
622 method_offsets_index_ = 0u;
623 return true;
624 }
625
626 bool EndClass() {
627 ++oat_class_index_;
628 return DexMethodVisitor::EndClass();
629 }
630
631 protected:
632 size_t oat_class_index_;
633 size_t method_offsets_index_;
634};
635
636class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
637 public:
638 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
639 : DexMethodVisitor(writer, offset),
640 compiled_methods_(),
641 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000642 size_t num_classes = 0u;
643 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
644 num_classes += oat_dex_file.class_offsets_.size();
645 }
646 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100647 compiled_methods_.reserve(256u);
648 }
649
650 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
651 DexMethodVisitor::StartClass(dex_file, class_def_index);
652 compiled_methods_.clear();
653 num_non_null_compiled_methods_ = 0u;
654 return true;
655 }
656
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300657 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
658 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100659 // Fill in the compiled_methods_ array for methods that have a
660 // CompiledMethod. We track the number of non-null entries in
661 // num_non_null_compiled_methods_ since we only want to allocate
662 // OatMethodOffsets for the compiled methods.
663 uint32_t method_idx = it.GetMemberIndex();
664 CompiledMethod* compiled_method =
665 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
666 compiled_methods_.push_back(compiled_method);
667 if (compiled_method != nullptr) {
668 ++num_non_null_compiled_methods_;
669 }
670 return true;
671 }
672
673 bool EndClass() {
674 ClassReference class_ref(dex_file_, class_def_index_);
675 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
676 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700677 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100678 status = compiled_class->GetStatus();
679 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
680 status = mirror::Class::kStatusError;
681 } else {
682 status = mirror::Class::kStatusNotReady;
683 }
684
Vladimir Marko49b0f452015-12-10 13:49:19 +0000685 writer_->oat_classes_.emplace_back(offset_,
686 compiled_methods_,
687 num_non_null_compiled_methods_,
688 status);
689 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100690 return DexMethodVisitor::EndClass();
691 }
692
693 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000694 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100695 size_t num_non_null_compiled_methods_;
696};
697
698class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
699 public:
700 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100701 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100702 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100703 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100704 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
705 }
706
707 bool EndClass() {
708 OatDexMethodVisitor::EndClass();
709 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100710 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100711 }
712 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100713 }
714
715 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700716 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000717 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
719
720 if (compiled_method != nullptr) {
721 // Derived from CompiledMethod.
722 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723
Vladimir Marko35831e82015-09-11 11:59:18 +0100724 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
725 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800726 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800727
David Srbecky009e2a62015-04-15 02:46:30 +0100728 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Markoc74658b2015-03-31 10:26:41 +0100729 bool deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800730 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000731 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000732 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
733 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800734 // Duplicate methods, we want the same code for both of them so that the oat writer puts
735 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800736 deduped = true;
737 } else {
738 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
739 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000740 } else {
741 auto lb = dedupe_map_.lower_bound(compiled_method);
742 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
743 quick_code_offset = lb->second;
744 deduped = true;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000745 } else {
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000746 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
747 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
David Srbecky009e2a62015-04-15 02:46:30 +0100748 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800749 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100750
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100751 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000752 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100753 // TODO: Should this be a hard failure?
754 LOG(WARNING) << "Multiple definitions of "
755 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000756 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
757 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100758 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000759 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100760 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800761 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762
Elliott Hughes956af0f2014-12-11 14:34:28 -0800763 // Update quick method header.
764 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
765 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
766 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
767 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100768 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
769 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100770 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800771 uint32_t gc_map_offset = method_header->gc_map_offset_;
772 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
773 // to 0-offset and we need to adjust it by code_offset.
774 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100775 if (mapping_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800776 mapping_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100777 DCHECK_LT(mapping_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800778 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100779 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800780 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100781 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800782 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100783 if (gc_map_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800784 gc_map_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100785 DCHECK_LT(gc_map_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800786 }
787 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
788 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
789 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
790 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
791 gc_map_offset, frame_size_in_bytes, core_spill_mask,
792 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100793
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000794 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800795 // Update offsets. (Checksum is updated when writing.)
796 offset_ += sizeof(*method_header); // Method header is prepended before code.
797 offset_ += code_size;
798 // Record absolute patch locations.
799 if (!compiled_method->GetPatches().empty()) {
800 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
801 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000802 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100803 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100804 }
805 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 }
Alex Light78382fa2014-06-06 15:45:32 -0700808
David Srbecky91cc06c2016-03-07 16:13:58 +0000809 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000810 // Exclude quickened dex methods (code_size == 0) since they have no native code.
811 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
812 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800813 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000814 debug::MethodDebugInfo info = debug::MethodDebugInfo();
815 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000816 info.dex_file = dex_file_;
817 info.class_def_index = class_def_index_;
818 info.dex_method_index = it.GetMemberIndex();
819 info.access_flags = it.GetMethodAccessFlags();
820 info.code_item = it.GetMethodCodeItem();
821 info.isa = compiled_method->GetInstructionSet();
822 info.deduped = deduped;
823 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
824 info.is_optimized = method_header->IsOptimized();
825 info.is_code_address_text_relative = true;
826 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
827 info.code_size = code_size;
828 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
829 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
830 info.cfi = compiled_method->GetCFIInfo();
831 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833
834 if (kIsDebugBuild) {
835 // We expect GC maps except when the class hasn't been verified or the method is native.
836 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
837 ClassReference class_ref(dex_file_, class_def_index_);
838 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
839 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700840 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841 status = compiled_class->GetStatus();
842 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
843 status = mirror::Class::kStatusError;
844 } else {
845 status = mirror::Class::kStatusNotReady;
846 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100847 ArrayRef<const uint8_t> gc_map = compiled_method->GetGcMap();
848 if (!gc_map.empty()) {
849 size_t gc_map_size = gc_map.size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700850 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100851 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
Vladimir Marko35831e82015-09-11 11:59:18 +0100852 << gc_map_size << " " << (is_native ? "true" : "false") << " "
Nicolas Geoffray39468442014-09-02 15:17:15 +0100853 << (status < mirror::Class::kStatusVerified) << " " << status << " "
854 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
855 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100856 }
857
858 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
859 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
860 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100861 ++method_offsets_index_;
862 }
863
864 return true;
865 }
866
867 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000868 struct CodeOffsetsKeyComparator {
869 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100870 // Code is deduplicated by CompilerDriver, compare only data pointers.
871 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
872 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000873 }
874 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100875 if (UNLIKELY(lhs->GetMappingTable().data() != rhs->GetMappingTable().data())) {
876 return lhs->GetMappingTable().data() < rhs->GetMappingTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000877 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100878 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
879 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000880 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100881 if (UNLIKELY(lhs->GetGcMap().data() != rhs->GetGcMap().data())) {
882 return lhs->GetGcMap().data() < rhs->GetGcMap().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000883 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100884 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
885 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000886 }
887 return false;
888 }
889 };
890
David Srbecky009e2a62015-04-15 02:46:30 +0100891 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
892 const ClassDataItemIterator& it,
893 uint32_t thumb_offset) {
894 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100895 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100896 offset_ = compiled_method->AlignCode(offset_);
897 DCHECK_ALIGNED_PARAM(offset_,
898 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
899 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
900 }
901
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100902 // Deduplication is already done on a pointer basis by the compiler driver,
903 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100904 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100905
David Srbecky009e2a62015-04-15 02:46:30 +0100906 // Cache of compiler's --debuggable option.
907 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100908};
909
910template <typename DataAccess>
911class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
912 public:
913 InitMapMethodVisitor(OatWriter* writer, size_t offset)
914 : OatDexMethodVisitor(writer, offset) {
915 }
916
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700917 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700918 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000919 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
921
922 if (compiled_method != nullptr) {
923 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
924 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
925
Vladimir Marko35831e82015-09-11 11:59:18 +0100926 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
927 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100928 if (map_size != 0u) {
Vladimir Marko35831e82015-09-11 11:59:18 +0100929 auto lb = dedupe_map_.lower_bound(map.data());
930 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map.data(), lb->first)) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100931 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100932 } else {
933 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Marko35831e82015-09-11 11:59:18 +0100934 dedupe_map_.PutBefore(lb, map.data(), offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100935 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100936 }
937 }
938 ++method_offsets_index_;
939 }
940
941 return true;
942 }
943
944 private:
945 // Deduplication is already done on a pointer basis by the compiler driver,
946 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100947 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100948};
949
950class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
951 public:
952 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800953 : OatDexMethodVisitor(writer, offset),
954 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100955 }
956
957 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700958 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800959 const DexFile::TypeId& type_id =
960 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
961 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
962 // Skip methods that are not in the image.
963 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
964 return true;
965 }
966
Vladimir Marko49b0f452015-12-10 13:49:19 +0000967 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100968 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
969
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800970 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100971 if (compiled_method != nullptr) {
972 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
973 offsets = oat_class->method_offsets_[method_offsets_index_];
974 ++method_offsets_index_;
975 }
976
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100977 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100978 // Unchecked as we hold mutator_lock_ on entry.
979 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800980 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700981 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
982 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800983 ArtMethod* method;
984 if (writer_->HasBootImage()) {
985 const InvokeType invoke_type = it.GetMethodInvokeType(
986 dex_file_->GetClassDef(class_def_index_));
987 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
988 *dex_file_,
989 it.GetMemberIndex(),
990 dex_cache,
991 ScopedNullHandle<mirror::ClassLoader>(),
992 nullptr,
993 invoke_type);
994 if (method == nullptr) {
995 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
996 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
997 soa.Self()->AssertPendingException();
998 mirror::Throwable* exc = soa.Self()->GetException();
999 std::string dump = exc->Dump();
1000 LOG(FATAL) << dump;
1001 UNREACHABLE();
1002 }
1003 } else {
1004 // Should already have been resolved by the compiler, just peek into the dex cache.
1005 // It may not be resolved if the class failed to verify, in this case, don't set the
1006 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1007 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001008 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001009 if (method != nullptr &&
1010 compiled_method != nullptr &&
1011 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001012 method->SetEntryPointFromQuickCompiledCodePtrSize(
1013 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1014 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001015
1016 return true;
1017 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001018
1019 protected:
1020 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001021};
1022
1023class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1024 public:
1025 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001026 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001027 : OatDexMethodVisitor(writer, relative_offset),
1028 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001029 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001030 soa_(Thread::Current()),
1031 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001032 class_linker_(Runtime::Current()->GetClassLinker()),
1033 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001034 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001035 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001036 // If we're creating the image, the address space must be ready so that we can apply patches.
1037 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001038 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001039 }
1040
Vladimir Markof4da6752014-08-01 19:04:18 +01001041 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001042 }
1043
1044 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -07001045 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001046 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1047 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001048 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markof4da6752014-08-01 19:04:18 +01001049 }
1050 return true;
1051 }
1052
Mathieu Chartier90443472015-07-16 20:32:27 -07001053 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001054 bool result = OatDexMethodVisitor::EndClass();
1055 if (oat_class_index_ == writer_->oat_classes_.size()) {
1056 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001057 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001058 if (UNLIKELY(offset_ == 0u)) {
1059 PLOG(ERROR) << "Failed to write final relative call thunks";
1060 result = false;
1061 }
1062 }
1063 return result;
1064 }
1065
1066 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -07001067 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001068 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001069 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1070
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001071 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1072 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001073 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001074 size_t file_offset = file_offset_;
1075 OutputStream* out = out_;
1076
Vladimir Marko35831e82015-09-11 11:59:18 +01001077 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1078 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001079
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001080 // Deduplicate code arrays.
1081 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1082 if (method_offsets.code_offset_ > offset_) {
1083 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1084 if (offset_ == 0u) {
1085 ReportWriteFailure("relative call thunk", it);
1086 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001087 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001088 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1089 uint32_t aligned_code_delta = aligned_offset - offset_;
1090 if (aligned_code_delta != 0) {
1091 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1092 ReportWriteFailure("code alignment padding", it);
1093 return false;
1094 }
1095 offset_ += aligned_code_delta;
1096 DCHECK_OFFSET_();
1097 }
1098 DCHECK_ALIGNED_PARAM(offset_,
1099 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1100 DCHECK_EQ(method_offsets.code_offset_,
1101 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1102 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1103 const OatQuickMethodHeader& method_header =
1104 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +00001105 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001106 ReportWriteFailure("method header", it);
1107 return false;
1108 }
1109 writer_->size_method_header_ += sizeof(method_header);
1110 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001111 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001112
1113 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001114 patched_code_.assign(quick_code.begin(), quick_code.end());
1115 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001116 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001117 uint32_t literal_offset = patch.LiteralOffset();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001118 if (patch.Type() == kLinkerPatchCallRelative) {
1119 // NOTE: Relative calls across oat files are not supported.
1120 uint32_t target_offset = GetTargetOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001121 writer_->relative_patcher_->PatchCall(&patched_code_,
1122 literal_offset,
1123 offset_ + literal_offset,
1124 target_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001125 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1126 uint32_t target_offset = GetDexCacheOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001127 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_,
1128 patch,
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001129 offset_ + literal_offset,
1130 target_offset);
1131 } else if (patch.Type() == kLinkerPatchCall) {
1132 uint32_t target_offset = GetTargetOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001133 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001134 } else if (patch.Type() == kLinkerPatchMethod) {
1135 ArtMethod* method = GetTargetMethod(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001136 PatchMethodAddress(&patched_code_, literal_offset, method);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001137 } else if (patch.Type() == kLinkerPatchType) {
1138 mirror::Class* type = GetTargetType(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001139 PatchObjectAddress(&patched_code_, literal_offset, type);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001140 }
1141 }
1142 }
1143
Vladimir Marko49b0f452015-12-10 13:49:19 +00001144 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001145 ReportWriteFailure("method code", it);
1146 return false;
1147 }
1148 writer_->size_code_ += code_size;
1149 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001150 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001151 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001152 ++method_offsets_index_;
1153 }
1154
1155 return true;
1156 }
1157
1158 private:
1159 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001160 const size_t file_offset_;
1161 const ScopedObjectAccess soa_;
1162 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001163 ClassLinker* const class_linker_;
1164 mirror::DexCache* dex_cache_;
1165 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001166
1167 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1168 PLOG(ERROR) << "Failed to write " << what << " for "
1169 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1170 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001171
Mathieu Chartiere401d142015-04-22 13:56:20 -07001172 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001173 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001174 MethodReference ref = patch.TargetMethod();
1175 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001176 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1177 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001178 ArtMethod* method = dex_cache->GetResolvedMethod(
1179 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001180 CHECK(method != nullptr);
1181 return method;
1182 }
1183
Mathieu Chartier90443472015-07-16 20:32:27 -07001184 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001185 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1186 // If there's no new compiled code, either we're compiling an app and the target method
1187 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001188 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001190 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001191 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1192 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1193 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001194 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001195 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1196 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1197 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1198 target_offset = PointerToLowMemUInt32(oat_code_offset);
1199 } else {
1200 target_offset = target->IsNative()
1201 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1202 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1203 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001204 }
1205 return target_offset;
1206 }
1207
1208 mirror::Class* GetTargetType(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001209 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001210 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001211 ? dex_cache_ : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001212 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1213 CHECK(type != nullptr);
1214 return type;
1215 }
1216
Mathieu Chartier90443472015-07-16 20:32:27 -07001217 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001218 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001219 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1220 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1221 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1222 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001223 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001224 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001225 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1226 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001227 }
1228 }
1229
Vladimir Markof4da6752014-08-01 19:04:18 +01001230 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001231 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001232 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001233 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001234 } else {
1235 // NOTE: We're using linker patches for app->boot references when the image can
1236 // be relocated and therefore we need to emit .oat_patches. We're not using this
1237 // for app->app references, so check that the object is in the image space.
1238 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001239 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001240 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001241 uint32_t address = PointerToLowMemUInt32(object);
1242 DCHECK_LE(offset + 4, code->size());
1243 uint8_t* data = &(*code)[offset];
1244 data[0] = address & 0xffu;
1245 data[1] = (address >> 8) & 0xffu;
1246 data[2] = (address >> 16) & 0xffu;
1247 data[3] = (address >> 24) & 0xffu;
1248 }
1249
Mathieu Chartiere401d142015-04-22 13:56:20 -07001250 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001251 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001252 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001253 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001254 } else if (kIsDebugBuild) {
1255 // NOTE: We're using linker patches for app->boot references when the image can
1256 // be relocated and therefore we need to emit .oat_patches. We're not using this
1257 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001258 std::vector<gc::space::ImageSpace*> image_spaces =
1259 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1260 bool contains_method = false;
1261 for (gc::space::ImageSpace* image_space : image_spaces) {
1262 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1263 contains_method |=
1264 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1265 }
1266 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001267 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001268 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001269 uint32_t address = PointerToLowMemUInt32(method);
1270 DCHECK_LE(offset + 4, code->size());
1271 uint8_t* data = &(*code)[offset];
1272 data[0] = address & 0xffu;
1273 data[1] = (address >> 8) & 0xffu;
1274 data[2] = (address >> 16) & 0xffu;
1275 data[3] = (address >> 24) & 0xffu;
1276 }
1277
Vladimir Markof4da6752014-08-01 19:04:18 +01001278 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001279 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001280 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001281 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001282 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1283 // TODO: Clean up offset types.
1284 // The target_offset must be treated as signed for cross-oat patching.
1285 const void* target = reinterpret_cast<const void*>(
1286 writer_->image_writer_->GetOatDataBegin(oat_index) +
1287 static_cast<int32_t>(target_offset));
1288 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001289 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001290 DCHECK_LE(offset + 4, code->size());
1291 uint8_t* data = &(*code)[offset];
1292 data[0] = address & 0xffu;
1293 data[1] = (address >> 8) & 0xffu;
1294 data[2] = (address >> 16) & 0xffu;
1295 data[3] = (address >> 24) & 0xffu;
1296 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297};
1298
1299template <typename DataAccess>
1300class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1301 public:
1302 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001303 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001304 : OatDexMethodVisitor(writer, relative_offset),
1305 out_(out),
1306 file_offset_(file_offset) {
1307 }
1308
1309 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001310 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001311 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1312
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001313 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001314 size_t file_offset = file_offset_;
1315 OutputStream* out = out_;
1316
1317 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1318 ++method_offsets_index_;
1319
1320 // Write deduplicated map.
Vladimir Marko35831e82015-09-11 11:59:18 +01001321 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
1322 size_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001323 DCHECK((map_size == 0u && map_offset == 0u) ||
1324 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001325 << map_size << " " << map_offset << " " << offset_ << " "
1326 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001327 if (map_size != 0u && map_offset == offset_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001328 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001329 ReportWriteFailure(it);
1330 return false;
1331 }
1332 offset_ += map_size;
1333 }
1334 DCHECK_OFFSET_();
1335 }
1336
1337 return true;
1338 }
1339
1340 private:
1341 OutputStream* const out_;
1342 size_t const file_offset_;
1343
1344 void ReportWriteFailure(const ClassDataItemIterator& it) {
1345 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1346 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1347 }
1348};
1349
1350// Visit all methods from all classes in all dex files with the specified visitor.
1351bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1352 for (const DexFile* dex_file : *dex_files_) {
1353 const size_t class_def_count = dex_file->NumClassDefs();
1354 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1355 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1356 return false;
1357 }
1358 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001359 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001360 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001361 ClassDataItemIterator it(*dex_file, class_data);
1362 while (it.HasNextStaticField()) {
1363 it.Next();
1364 }
1365 while (it.HasNextInstanceField()) {
1366 it.Next();
1367 }
1368 size_t class_def_method_index = 0u;
1369 while (it.HasNextDirectMethod()) {
1370 if (!visitor->VisitMethod(class_def_method_index, it)) {
1371 return false;
1372 }
1373 ++class_def_method_index;
1374 it.Next();
1375 }
1376 while (it.HasNextVirtualMethod()) {
1377 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1378 return false;
1379 }
1380 ++class_def_method_index;
1381 it.Next();
1382 }
1383 }
1384 if (UNLIKELY(!visitor->EndClass())) {
1385 return false;
1386 }
1387 }
1388 }
1389 return true;
1390}
1391
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001392size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1393 const InstructionSetFeatures* instruction_set_features,
1394 uint32_t num_dex_files,
1395 SafeMap<std::string, std::string>* key_value_store) {
1396 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1397 oat_header_.reset(OatHeader::Create(instruction_set,
1398 instruction_set_features,
1399 num_dex_files,
1400 key_value_store));
1401 size_oat_header_ += sizeof(OatHeader);
1402 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001403 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001404}
1405
1406size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001407 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1408 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001409 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001410 oat_dex_file.offset_ = offset;
1411 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001412 }
1413 return offset;
1414}
1415
Brian Carlstrom389efb02012-01-11 12:06:26 -08001416size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001417 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001418 InitOatClassesMethodVisitor visitor(this, offset);
1419 bool success = VisitDexMethods(&visitor);
1420 CHECK(success);
1421 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001422
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 // Update oat_dex_files_.
1424 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001425 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1426 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001427 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001428 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001429 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001430 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001431 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001432 CHECK(oat_class_it == oat_classes_.end());
1433
1434 return offset;
1435}
1436
1437size_t OatWriter::InitOatMaps(size_t offset) {
1438 #define VISIT(VisitorType) \
1439 do { \
1440 VisitorType visitor(this, offset); \
1441 bool success = VisitDexMethods(&visitor); \
1442 DCHECK(success); \
1443 offset = visitor.GetOffset(); \
1444 } while (false)
1445
1446 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1447 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1448 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1449
1450 #undef VISIT
1451
Brian Carlstrome24fa612011-09-29 00:53:55 -07001452 return offset;
1453}
1454
1455size_t OatWriter::InitOatCode(size_t offset) {
1456 // calculate the offsets within OatHeader to executable code
1457 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001458 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001459 // required to be on a new page boundary
1460 offset = RoundUp(offset, kPageSize);
1461 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001462 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001463 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001464 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465
Ian Rogers848871b2013-08-05 10:56:33 -07001466 #define DO_TRAMPOLINE(field, fn_name) \
1467 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001468 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1469 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001470 field.reset(compiler_driver_->Create ## fn_name()); \
1471 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001472
Ian Rogers848871b2013-08-05 10:56:33 -07001473 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001474 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001475 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001476 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1477 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001478
Ian Rogers848871b2013-08-05 10:56:33 -07001479 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001480 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001481 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1482 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1483 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001484 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001485 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001486 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001487 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001488 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001489 return offset;
1490}
1491
1492size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001493 #define VISIT(VisitorType) \
1494 do { \
1495 VisitorType visitor(this, offset); \
1496 bool success = VisitDexMethods(&visitor); \
1497 DCHECK(success); \
1498 offset = visitor.GetOffset(); \
1499 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001500
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001501 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001502 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001503 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001504 }
Logan Chien8b977d32012-02-21 19:14:55 +08001505
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001506 #undef VISIT
1507
Brian Carlstrome24fa612011-09-29 00:53:55 -07001508 return offset;
1509}
1510
David Srbeckybc90fd02015-04-22 19:40:27 +01001511bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001512 CHECK(write_state_ == WriteState::kWriteRoData);
1513
1514 if (!WriteClassOffsets(out)) {
1515 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001516 return false;
1517 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001518
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001519 if (!WriteClasses(out)) {
1520 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001521 return false;
1522 }
1523
Vladimir Markof4da6752014-08-01 19:04:18 +01001524 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001525 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001526 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1527 return false;
1528 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001529 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001530 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001531 relative_offset = WriteMaps(out, file_offset, relative_offset);
1532 if (relative_offset == 0) {
1533 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1534 return false;
1535 }
1536
David Srbeckybc90fd02015-04-22 19:40:27 +01001537 // Write padding.
1538 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1539 relative_offset += size_executable_offset_alignment_;
1540 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1541 size_t expected_file_offset = file_offset + relative_offset;
1542 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1543 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1544 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1545 return 0;
1546 }
1547 DCHECK_OFFSET();
1548
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001549 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001550 return true;
1551}
1552
1553bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001554 CHECK(write_state_ == WriteState::kWriteText);
1555
Vladimir Marko944da602016-02-19 12:27:55 +00001556 SetMultiOatRelativePatcherAdjustment();
1557
David Srbeckybc90fd02015-04-22 19:40:27 +01001558 const size_t file_offset = oat_data_offset_;
1559 size_t relative_offset = oat_header_->GetExecutableOffset();
1560 DCHECK_OFFSET();
1561
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001562 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001563 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001564 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001565 return false;
1566 }
1567
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001568 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1569 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001570 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001571 return false;
1572 }
1573
Vladimir Markof4da6752014-08-01 19:04:18 +01001574 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001575 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001576 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1577 return false;
1578 }
1579
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001580 if (kIsDebugBuild) {
1581 uint32_t size_total = 0;
1582 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001583 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001584 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001585
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001586 DO_STAT(size_dex_file_alignment_);
1587 DO_STAT(size_executable_offset_alignment_);
1588 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001589 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001590 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001591 DO_STAT(size_interpreter_to_interpreter_bridge_);
1592 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1593 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001594 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001595 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001596 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001597 DO_STAT(size_quick_to_interpreter_bridge_);
1598 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001599 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001600 DO_STAT(size_code_);
1601 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001602 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001603 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001604 DO_STAT(size_mapping_table_);
1605 DO_STAT(size_vmap_table_);
1606 DO_STAT(size_gc_map_);
1607 DO_STAT(size_oat_dex_file_location_size_);
1608 DO_STAT(size_oat_dex_file_location_data_);
1609 DO_STAT(size_oat_dex_file_location_checksum_);
1610 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001611 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001612 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001613 DO_STAT(size_oat_lookup_table_alignment_);
1614 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001615 DO_STAT(size_oat_class_offsets_alignment_);
1616 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001617 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001618 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001619 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001620 DO_STAT(size_oat_class_method_offsets_);
1621 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001622
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001623 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001624 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001625 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001626 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001627
Vladimir Markof4da6752014-08-01 19:04:18 +01001628 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001629 CHECK_EQ(size_, relative_offset);
1630
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001631 write_state_ = WriteState::kWriteHeader;
1632 return true;
1633}
1634
1635bool OatWriter::WriteHeader(OutputStream* out,
1636 uint32_t image_file_location_oat_checksum,
1637 uintptr_t image_file_location_oat_begin,
1638 int32_t image_patch_delta) {
1639 CHECK(write_state_ == WriteState::kWriteHeader);
1640
1641 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1642 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1643 if (compiler_driver_->IsBootImage()) {
1644 CHECK_EQ(image_patch_delta, 0);
1645 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1646 } else {
1647 CHECK_ALIGNED(image_patch_delta, kPageSize);
1648 oat_header_->SetImagePatchDelta(image_patch_delta);
1649 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001650 oat_header_->UpdateChecksumWithHeaderData();
1651
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001652 const size_t file_offset = oat_data_offset_;
1653
1654 off_t current_offset = out->Seek(0, kSeekCurrent);
1655 if (current_offset == static_cast<off_t>(-1)) {
1656 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1657 return false;
1658 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001659 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001660 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1661 return false;
1662 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001663 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001664
1665 // Flush all other data before writing the header.
1666 if (!out->Flush()) {
1667 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1668 return false;
1669 }
1670 // Write the header.
1671 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001672 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001673 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1674 return false;
1675 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001676 // Flush the header data.
1677 if (!out->Flush()) {
1678 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001679 return false;
1680 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001681
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001682 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1683 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1684 return false;
1685 }
1686 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1687
1688 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001689 return true;
1690}
1691
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001692bool OatWriter::WriteClassOffsets(OutputStream* out) {
1693 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1694 if (oat_dex_file.class_offsets_offset_ != 0u) {
1695 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1696 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1697 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1698 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1699 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001700 return false;
1701 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001702 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1703 return false;
1704 }
1705 }
1706 }
1707 return true;
1708}
1709
1710bool OatWriter::WriteClasses(OutputStream* out) {
1711 for (OatClass& oat_class : oat_classes_) {
1712 if (!oat_class.Write(this, out, oat_data_offset_)) {
1713 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1714 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001715 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001716 }
1717 return true;
1718}
1719
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001720size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1721 #define VISIT(VisitorType) \
1722 do { \
1723 VisitorType visitor(this, out, file_offset, relative_offset); \
1724 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1725 return 0; \
1726 } \
1727 relative_offset = visitor.GetOffset(); \
1728 } while (false)
1729
1730 size_t gc_maps_offset = relative_offset;
1731 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1732 size_gc_map_ = relative_offset - gc_maps_offset;
1733
1734 size_t mapping_tables_offset = relative_offset;
1735 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1736 size_mapping_table_ = relative_offset - mapping_tables_offset;
1737
1738 size_t vmap_tables_offset = relative_offset;
1739 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1740 size_vmap_table_ = relative_offset - vmap_tables_offset;
1741
1742 #undef VISIT
1743
1744 return relative_offset;
1745}
1746
1747size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001748 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001749 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001750
Ian Rogers848871b2013-08-05 10:56:33 -07001751 #define DO_TRAMPOLINE(field) \
1752 do { \
1753 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1754 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001755 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001756 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001757 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001758 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001759 return false; \
1760 } \
1761 size_ ## field += field->size(); \
1762 relative_offset += alignment_padding + field->size(); \
1763 DCHECK_OFFSET(); \
1764 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001765
Ian Rogers848871b2013-08-05 10:56:33 -07001766 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001767 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001768 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001769 DO_TRAMPOLINE(quick_resolution_trampoline_);
1770 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1771 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001772 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001773 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001774}
1775
Ian Rogers3d504072014-03-01 09:16:49 -08001776size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001777 const size_t file_offset,
1778 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001779 #define VISIT(VisitorType) \
1780 do { \
1781 VisitorType visitor(this, out, file_offset, relative_offset); \
1782 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1783 return 0; \
1784 } \
1785 relative_offset = visitor.GetOffset(); \
1786 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001787
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001788 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001789
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001790 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001791
Vladimir Markob163bb72015-03-31 21:49:49 +01001792 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1793 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1794 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1795
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001796 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001797}
1798
Vladimir Marko944da602016-02-19 12:27:55 +00001799bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001800 // Get the elf file offset of the oat file.
1801 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1802 if (raw_file_offset == static_cast<off_t>(-1)) {
1803 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1804 return false;
1805 }
1806 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1807 return true;
1808}
1809
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001810bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1811 // Read the dex file header and perform minimal verification.
1812 uint8_t raw_header[sizeof(DexFile::Header)];
1813 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1814 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1815 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1816 return false;
1817 }
1818 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1819 return false;
1820 }
1821
1822 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1823 oat_dex_file->dex_file_size_ = header->file_size_;
1824 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1825 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1826 return true;
1827}
1828
1829bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1830 if (!DexFile::IsMagicValid(raw_header)) {
1831 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1832 return false;
1833 }
1834 if (!DexFile::IsVersionValid(raw_header)) {
1835 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1836 return false;
1837 }
1838 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1839 if (header->file_size_ < sizeof(DexFile::Header)) {
1840 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1841 << " File: " << location;
1842 return false;
1843 }
1844 return true;
1845}
1846
1847bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1848 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1849
1850 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001851 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001852 return false;
1853 }
1854
1855 // Write dex files.
1856 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1857 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1858 return false;
1859 }
1860 }
1861
1862 // Close sources.
1863 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1864 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1865 }
1866 zipped_dex_files_.clear();
1867 zip_archives_.clear();
1868 raw_dex_files_.clear();
1869 return true;
1870}
1871
1872bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1873 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1874 return false;
1875 }
1876 if (oat_dex_file->source_.IsZipEntry()) {
1877 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1878 return false;
1879 }
1880 } else if (oat_dex_file->source_.IsRawFile()) {
1881 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1882 return false;
1883 }
1884 } else {
1885 DCHECK(oat_dex_file->source_.IsRawData());
1886 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1887 return false;
1888 }
1889 }
1890
1891 // Update current size and account for the written data.
1892 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1893 size_ += oat_dex_file->dex_file_size_;
1894 size_dex_file_ += oat_dex_file->dex_file_size_;
1895 return true;
1896}
1897
1898bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1899 // Dex files are required to be 4 byte aligned.
1900 size_t original_offset = size_;
1901 size_t offset = RoundUp(original_offset, 4);
1902 size_dex_file_alignment_ += offset - original_offset;
1903
1904 // Seek to the start of the dex file and flush any pending operations in the stream.
1905 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1906 uint32_t start_offset = oat_data_offset_ + offset;
1907 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1908 if (actual_offset != static_cast<off_t>(start_offset)) {
1909 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1910 << " Expected: " << start_offset
1911 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1912 return false;
1913 }
1914 if (!out->Flush()) {
1915 PLOG(ERROR) << "Failed to flush before writing dex file."
1916 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1917 return false;
1918 }
1919 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1920 if (actual_offset != static_cast<off_t>(start_offset)) {
1921 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1922 << " Expected: " << start_offset
1923 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1924 return false;
1925 }
1926
1927 size_ = offset;
1928 oat_dex_file->dex_file_offset_ = offset;
1929 return true;
1930}
1931
1932bool OatWriter::WriteDexFile(OutputStream* rodata,
1933 File* file,
1934 OatDexFile* oat_dex_file,
1935 ZipEntry* dex_file) {
1936 size_t start_offset = oat_data_offset_ + size_;
1937 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1938
1939 // Extract the dex file and get the extracted size.
1940 std::string error_msg;
1941 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1942 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1943 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1944 return false;
1945 }
1946 if (file->Flush() != 0) {
1947 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1948 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1949 return false;
1950 }
1951 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1952 if (extracted_end == static_cast<off_t>(-1)) {
1953 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1954 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1955 return false;
1956 }
1957 if (extracted_end < static_cast<off_t>(start_offset)) {
1958 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1959 << " Start: " << start_offset
1960 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1961 return false;
1962 }
1963 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1964 if (extracted_size < sizeof(DexFile::Header)) {
1965 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1966 << extracted_size << " File: " << oat_dex_file->GetLocation();
1967 return false;
1968 }
1969
1970 // Read the dex file header and extract required data to OatDexFile.
1971 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1972 if (actual_offset != static_cast<off_t>(start_offset)) {
1973 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1974 << " Expected: " << start_offset
1975 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1976 return false;
1977 }
1978 if (!ReadDexFileHeader(file, oat_dex_file)) {
1979 return false;
1980 }
1981 if (extracted_size < oat_dex_file->dex_file_size_) {
1982 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1983 << " file size from header: " << oat_dex_file->dex_file_size_
1984 << " File: " << oat_dex_file->GetLocation();
1985 return false;
1986 }
1987
1988 // Override the checksum from header with the CRC from ZIP entry.
1989 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1990
1991 // Seek both file and stream to the end offset.
1992 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1993 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1994 if (actual_offset != static_cast<off_t>(end_offset)) {
1995 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1996 << " Expected: " << end_offset
1997 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1998 return false;
1999 }
2000 actual_offset = rodata->Seek(end_offset, kSeekSet);
2001 if (actual_offset != static_cast<off_t>(end_offset)) {
2002 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2003 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2004 return false;
2005 }
2006 if (!rodata->Flush()) {
2007 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2008 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2009 return false;
2010 }
2011
2012 // If we extracted more than the size specified in the header, truncate the file.
2013 if (extracted_size > oat_dex_file->dex_file_size_) {
2014 if (file->SetLength(end_offset) != 0) {
2015 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2016 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2017 return false;
2018 }
2019 }
2020
2021 return true;
2022}
2023
2024bool OatWriter::WriteDexFile(OutputStream* rodata,
2025 File* file,
2026 OatDexFile* oat_dex_file,
2027 File* dex_file) {
2028 size_t start_offset = oat_data_offset_ + size_;
2029 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2030
2031 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2032 if (input_offset != static_cast<off_t>(0)) {
2033 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2034 << " Expected: 0"
2035 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2036 return false;
2037 }
2038 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2039 return false;
2040 }
2041
2042 // Copy the input dex file using sendfile().
2043 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2044 PLOG(ERROR) << "Failed to copy dex file to oat file."
2045 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2046 return false;
2047 }
2048 if (file->Flush() != 0) {
2049 PLOG(ERROR) << "Failed to flush dex file."
2050 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2051 return false;
2052 }
2053
2054 // Check file position and seek the stream to the end offset.
2055 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2056 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2057 if (actual_offset != static_cast<off_t>(end_offset)) {
2058 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2059 << " Expected: " << end_offset
2060 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2061 return false;
2062 }
2063 actual_offset = rodata->Seek(end_offset, kSeekSet);
2064 if (actual_offset != static_cast<off_t>(end_offset)) {
2065 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2066 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2067 return false;
2068 }
2069 if (!rodata->Flush()) {
2070 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2071 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2072 return false;
2073 }
2074
2075 return true;
2076}
2077
2078bool OatWriter::WriteDexFile(OutputStream* rodata,
2079 OatDexFile* oat_dex_file,
2080 const uint8_t* dex_file) {
2081 // Note: The raw data has already been checked to contain the header
2082 // and all the data that the header specifies as the file size.
2083 DCHECK(dex_file != nullptr);
2084 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2085 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2086
2087 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2088 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2089 << " to " << rodata->GetLocation();
2090 return false;
2091 }
2092 if (!rodata->Flush()) {
2093 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2094 << " File: " << oat_dex_file->GetLocation();
2095 return false;
2096 }
2097
2098 // Update dex file size and resize class offsets in the OatDexFile.
2099 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2100 oat_dex_file->dex_file_size_ = header->file_size_;
2101 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2102 return true;
2103}
2104
2105bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2106 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2107
2108 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2109 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2110 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2111 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2112 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2113 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2114 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2115 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2116 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2117 return false;
2118 }
2119
2120 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2121 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2122
2123 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2124 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2125
2126 // Write OatDexFile.
2127 if (!oat_dex_file->Write(this, rodata)) {
2128 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2129 return false;
2130 }
2131 }
2132
2133 return true;
2134}
2135
2136bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2137 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2138
2139 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2140 if (file->SetLength(new_length) != 0) {
2141 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2142 << "File: " << file->GetPath();
2143 return false;
2144 }
2145 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2146 if (actual_offset != static_cast<off_t>(new_length)) {
2147 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2148 << " Actual: " << actual_offset << " Expected: " << new_length
2149 << " File: " << rodata->GetLocation();
2150 return false;
2151 }
2152 if (!rodata->Flush()) {
2153 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2154 << " File: " << rodata->GetLocation();
2155 return false;
2156 }
2157 return true;
2158}
2159
2160bool OatWriter::OpenDexFiles(
2161 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002162 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002163 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2164 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2165 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2166
2167 if (oat_dex_files_.empty()) {
2168 // Nothing to do.
2169 return true;
2170 }
2171
2172 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2173 size_t length = size_ - map_offset;
2174 std::string error_msg;
2175 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2176 PROT_READ | PROT_WRITE,
2177 MAP_SHARED,
2178 file->Fd(),
2179 oat_data_offset_ + map_offset,
2180 /* low_4gb */ false,
2181 file->GetPath().c_str(),
2182 &error_msg));
2183 if (dex_files_map == nullptr) {
2184 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2185 << " error: " << error_msg;
2186 return false;
2187 }
2188 std::vector<std::unique_ptr<const DexFile>> dex_files;
2189 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2190 // Make sure no one messed with input files while we were copying data.
2191 // At the very least we need consistent file size and number of class definitions.
2192 const uint8_t* raw_dex_file =
2193 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2194 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2195 // Note: ValidateDexFileHeader() already logged an error message.
2196 LOG(ERROR) << "Failed to verify written dex file header!"
2197 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2198 << " ~ " << static_cast<const void*>(raw_dex_file);
2199 return false;
2200 }
2201 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2202 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2203 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2204 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2205 << " Output: " << file->GetPath();
2206 return false;
2207 }
2208 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2209 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2210 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2211 << " Output: " << file->GetPath();
2212 return false;
2213 }
2214
2215 // Now, open the dex file.
2216 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2217 oat_dex_file.dex_file_size_,
2218 oat_dex_file.GetLocation(),
2219 oat_dex_file.dex_file_location_checksum_,
2220 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002221 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002222 &error_msg));
2223 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002224 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2225 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002226 return false;
2227 }
2228 }
2229
2230 *opened_dex_files_map = std::move(dex_files_map);
2231 *opened_dex_files = std::move(dex_files);
2232 return true;
2233}
2234
2235bool OatWriter::WriteTypeLookupTables(
2236 MemMap* opened_dex_files_map,
2237 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2238 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2239
2240 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2241 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2242 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2243 if (oat_dex_file->lookup_table_offset_ != 0u) {
2244 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2245 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2246 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2247 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2248 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2249 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2250 }
2251 }
2252
2253 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2254 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2255 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2256 return false;
2257 }
2258
2259 return true;
2260}
2261
Vladimir Markof4da6752014-08-01 19:04:18 +01002262bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2263 static const uint8_t kPadding[] = {
2264 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2265 };
2266 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2267 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2268 return false;
2269 }
2270 size_code_alignment_ += aligned_code_delta;
2271 return true;
2272}
2273
Vladimir Marko49b0f452015-12-10 13:49:19 +00002274bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2275 oat_header_->UpdateChecksum(data, size);
2276 return out->WriteFully(data, size);
2277}
2278
Vladimir Marko944da602016-02-19 12:27:55 +00002279void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2280 DCHECK(dex_files_ != nullptr);
2281 DCHECK(relative_patcher_ != nullptr);
2282 DCHECK_NE(oat_data_offset_, 0u);
2283 if (image_writer_ != nullptr && !dex_files_->empty()) {
2284 // The oat data begin may not be initialized yet but the oat file offset is ready.
2285 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2286 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2287 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002288 }
2289}
2290
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002291OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2292 DexFileSource source,
2293 CreateTypeLookupTable create_type_lookup_table)
2294 : source_(source),
2295 create_type_lookup_table_(create_type_lookup_table),
2296 dex_file_size_(0),
2297 offset_(0),
2298 dex_file_location_size_(strlen(dex_file_location)),
2299 dex_file_location_data_(dex_file_location),
2300 dex_file_location_checksum_(0u),
2301 dex_file_offset_(0u),
2302 class_offsets_offset_(0u),
2303 lookup_table_offset_(0u),
2304 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002305}
2306
2307size_t OatWriter::OatDexFile::SizeOf() const {
2308 return sizeof(dex_file_location_size_)
2309 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002310 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002311 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002312 + sizeof(class_offsets_offset_)
2313 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002314}
2315
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002316void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2317 DCHECK_EQ(lookup_table_offset_, 0u);
2318 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2319 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2320 if (table_size != 0u) {
2321 // Type tables are required to be 4 byte aligned.
2322 size_t original_offset = oat_writer->size_;
2323 size_t offset = RoundUp(original_offset, 4);
2324 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2325 lookup_table_offset_ = offset;
2326 oat_writer->size_ = offset + table_size;
2327 oat_writer->size_oat_lookup_table_ += table_size;
2328 }
2329 }
2330}
2331
2332void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2333 DCHECK_EQ(class_offsets_offset_, 0u);
2334 if (!class_offsets_.empty()) {
2335 // Class offsets are required to be 4 byte aligned.
2336 size_t original_offset = oat_writer->size_;
2337 size_t offset = RoundUp(original_offset, 4);
2338 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2339 class_offsets_offset_ = offset;
2340 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2341 }
2342}
2343
2344bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2345 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002346 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002347
Vladimir Marko49b0f452015-12-10 13:49:19 +00002348 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002349 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002350 return false;
2351 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002352 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002353
Vladimir Marko49b0f452015-12-10 13:49:19 +00002354 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002355 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002356 return false;
2357 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002358 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002359
Vladimir Marko49b0f452015-12-10 13:49:19 +00002360 if (!oat_writer->WriteData(out,
2361 &dex_file_location_checksum_,
2362 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002363 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002364 return false;
2365 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002366 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367
Vladimir Marko49b0f452015-12-10 13:49:19 +00002368 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002369 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002370 return false;
2371 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002372 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002373
2374 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2375 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2376 return false;
2377 }
2378 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2379
Vladimir Marko49b0f452015-12-10 13:49:19 +00002380 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002381 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2382 return false;
2383 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002384 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002385
2386 return true;
2387}
2388
2389bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002390 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002391 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2392 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002393 return false;
2394 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002395 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002396 return true;
2397}
2398
Brian Carlstromba150c32013-08-27 17:31:03 -07002399OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002400 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002401 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002402 mirror::Class::Status status)
2403 : compiled_methods_(compiled_methods) {
2404 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002405 CHECK_LE(num_non_null_compiled_methods, num_methods);
2406
Brian Carlstrom265091e2013-01-30 14:08:26 -08002407 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002408 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2409
2410 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2411 // apply when there are 0 methods, we just arbitrarily say that 0
2412 // methods means kOatClassNoneCompiled and that we won't use
2413 // kOatClassAllCompiled unless there is at least one compiled
2414 // method. This means in an interpretter only system, we can assert
2415 // that all classes are kOatClassNoneCompiled.
2416 if (num_non_null_compiled_methods == 0) {
2417 type_ = kOatClassNoneCompiled;
2418 } else if (num_non_null_compiled_methods == num_methods) {
2419 type_ = kOatClassAllCompiled;
2420 } else {
2421 type_ = kOatClassSomeCompiled;
2422 }
2423
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002424 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002425 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002426 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002427
2428 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2429 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002430 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002431 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2432 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2433 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2434 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002435 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002436 method_bitmap_size_ = 0;
2437 }
2438
2439 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002440 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002441 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002442 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2443 } else {
2444 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2445 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2446 if (type_ == kOatClassSomeCompiled) {
2447 method_bitmap_->SetBit(i);
2448 }
2449 }
2450 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002451}
2452
Brian Carlstrom265091e2013-01-30 14:08:26 -08002453size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2454 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002455 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2456 if (method_offset == 0) {
2457 return 0;
2458 }
2459 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002460}
2461
2462size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2463 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002464 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002465}
2466
2467size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002468 return sizeof(status_)
2469 + sizeof(type_)
2470 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2471 + method_bitmap_size_
2472 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002473}
2474
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002475bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002476 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002477 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002478 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002479 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002480 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002481 return false;
2482 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002483 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002484
2485 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002486 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002487 return false;
2488 }
2489 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002490
Brian Carlstromba150c32013-08-27 17:31:03 -07002491 if (method_bitmap_size_ != 0) {
2492 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002493 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002494 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002495 return false;
2496 }
2497 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002498
2499 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002500 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002501 return false;
2502 }
2503 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2504 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002505
2506 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002507 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002508 return false;
2509 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002510 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002511 return true;
2512}
2513
Brian Carlstrome24fa612011-09-29 00:53:55 -07002514} // namespace art