blob: 50f5aba061c7a1f1b0ccd836b594c58bceb78e9f [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();
810 if (compiler_options.GenerateAnyDebugInfo()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 // Record debug information for this function if we are doing that.
Elliott Hughes956af0f2014-12-11 14:34:28 -0800812 const uint32_t quick_code_start = quick_code_offset -
David Srbecky6f715892015-03-30 14:21:42 +0100813 writer_->oat_header_->GetExecutableOffset() - thumb_offset;
David Srbeckyc5bfa972016-02-05 15:49:10 +0000814 writer_->method_info_.push_back(debug::MethodDebugInfo {
David Srbecky0df9e1f2015-04-07 19:02:58 +0100815 dex_file_,
816 class_def_index_,
817 it.GetMemberIndex(),
818 it.GetMethodAccessFlags(),
819 it.GetMethodCodeItem(),
820 deduped,
David Srbecky91cc06c2016-03-07 16:13:58 +0000821 compiler_options.GetNativeDebuggable(),
David Srbecky0df9e1f2015-04-07 19:02:58 +0100822 quick_code_start,
823 quick_code_start + code_size,
824 compiled_method});
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100825 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100826
827 if (kIsDebugBuild) {
828 // We expect GC maps except when the class hasn't been verified or the method is native.
829 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
830 ClassReference class_ref(dex_file_, class_def_index_);
831 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
832 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700833 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100834 status = compiled_class->GetStatus();
835 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
836 status = mirror::Class::kStatusError;
837 } else {
838 status = mirror::Class::kStatusNotReady;
839 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100840 ArrayRef<const uint8_t> gc_map = compiled_method->GetGcMap();
841 if (!gc_map.empty()) {
842 size_t gc_map_size = gc_map.size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700843 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100844 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
Vladimir Marko35831e82015-09-11 11:59:18 +0100845 << gc_map_size << " " << (is_native ? "true" : "false") << " "
Nicolas Geoffray39468442014-09-02 15:17:15 +0100846 << (status < mirror::Class::kStatusVerified) << " " << status << " "
847 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
848 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100849 }
850
851 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
852 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
853 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100854 ++method_offsets_index_;
855 }
856
857 return true;
858 }
859
860 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000861 struct CodeOffsetsKeyComparator {
862 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100863 // Code is deduplicated by CompilerDriver, compare only data pointers.
864 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
865 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000866 }
867 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100868 if (UNLIKELY(lhs->GetMappingTable().data() != rhs->GetMappingTable().data())) {
869 return lhs->GetMappingTable().data() < rhs->GetMappingTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000870 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100871 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
872 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000873 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100874 if (UNLIKELY(lhs->GetGcMap().data() != rhs->GetGcMap().data())) {
875 return lhs->GetGcMap().data() < rhs->GetGcMap().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000876 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100877 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
878 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000879 }
880 return false;
881 }
882 };
883
David Srbecky009e2a62015-04-15 02:46:30 +0100884 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
885 const ClassDataItemIterator& it,
886 uint32_t thumb_offset) {
887 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100888 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100889 offset_ = compiled_method->AlignCode(offset_);
890 DCHECK_ALIGNED_PARAM(offset_,
891 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
892 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
893 }
894
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100895 // Deduplication is already done on a pointer basis by the compiler driver,
896 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100897 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100898
David Srbecky009e2a62015-04-15 02:46:30 +0100899 // Cache of compiler's --debuggable option.
900 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100901};
902
903template <typename DataAccess>
904class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
905 public:
906 InitMapMethodVisitor(OatWriter* writer, size_t offset)
907 : OatDexMethodVisitor(writer, offset) {
908 }
909
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700910 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700911 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000912 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100913 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
914
915 if (compiled_method != nullptr) {
916 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
917 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
918
Vladimir Marko35831e82015-09-11 11:59:18 +0100919 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
920 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100921 if (map_size != 0u) {
Vladimir Marko35831e82015-09-11 11:59:18 +0100922 auto lb = dedupe_map_.lower_bound(map.data());
923 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map.data(), lb->first)) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100924 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100925 } else {
926 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Marko35831e82015-09-11 11:59:18 +0100927 dedupe_map_.PutBefore(lb, map.data(), offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100928 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100929 }
930 }
931 ++method_offsets_index_;
932 }
933
934 return true;
935 }
936
937 private:
938 // Deduplication is already done on a pointer basis by the compiler driver,
939 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100940 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941};
942
943class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
944 public:
945 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800946 : OatDexMethodVisitor(writer, offset),
947 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100948 }
949
950 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700951 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952 const DexFile::TypeId& type_id =
953 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
954 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
955 // Skip methods that are not in the image.
956 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
957 return true;
958 }
959
Vladimir Marko49b0f452015-12-10 13:49:19 +0000960 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100961 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
962
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800963 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100964 if (compiled_method != nullptr) {
965 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
966 offsets = oat_class->method_offsets_[method_offsets_index_];
967 ++method_offsets_index_;
968 }
969
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100970 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100971 // Unchecked as we hold mutator_lock_ on entry.
972 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800973 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700974 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
975 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800976 ArtMethod* method;
977 if (writer_->HasBootImage()) {
978 const InvokeType invoke_type = it.GetMethodInvokeType(
979 dex_file_->GetClassDef(class_def_index_));
980 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
981 *dex_file_,
982 it.GetMemberIndex(),
983 dex_cache,
984 ScopedNullHandle<mirror::ClassLoader>(),
985 nullptr,
986 invoke_type);
987 if (method == nullptr) {
988 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
989 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
990 soa.Self()->AssertPendingException();
991 mirror::Throwable* exc = soa.Self()->GetException();
992 std::string dump = exc->Dump();
993 LOG(FATAL) << dump;
994 UNREACHABLE();
995 }
996 } else {
997 // Should already have been resolved by the compiler, just peek into the dex cache.
998 // It may not be resolved if the class failed to verify, in this case, don't set the
999 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1000 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001001 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001002 if (method != nullptr &&
1003 compiled_method != nullptr &&
1004 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001005 method->SetEntryPointFromQuickCompiledCodePtrSize(
1006 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1007 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001008
1009 return true;
1010 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001011
1012 protected:
1013 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001014};
1015
1016class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1017 public:
1018 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001019 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001020 : OatDexMethodVisitor(writer, relative_offset),
1021 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001022 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001023 soa_(Thread::Current()),
1024 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001025 class_linker_(Runtime::Current()->GetClassLinker()),
1026 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001027 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001028 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001029 // If we're creating the image, the address space must be ready so that we can apply patches.
1030 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001031 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001032 }
1033
Vladimir Markof4da6752014-08-01 19:04:18 +01001034 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001035 }
1036
1037 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -07001038 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001039 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1040 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001041 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markof4da6752014-08-01 19:04:18 +01001042 }
1043 return true;
1044 }
1045
Mathieu Chartier90443472015-07-16 20:32:27 -07001046 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001047 bool result = OatDexMethodVisitor::EndClass();
1048 if (oat_class_index_ == writer_->oat_classes_.size()) {
1049 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001050 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001051 if (UNLIKELY(offset_ == 0u)) {
1052 PLOG(ERROR) << "Failed to write final relative call thunks";
1053 result = false;
1054 }
1055 }
1056 return result;
1057 }
1058
1059 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -07001060 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001061 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001062 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1063
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001064 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1065 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001066 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001067 size_t file_offset = file_offset_;
1068 OutputStream* out = out_;
1069
Vladimir Marko35831e82015-09-11 11:59:18 +01001070 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1071 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001072
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001073 // Deduplicate code arrays.
1074 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1075 if (method_offsets.code_offset_ > offset_) {
1076 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1077 if (offset_ == 0u) {
1078 ReportWriteFailure("relative call thunk", it);
1079 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001080 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001081 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1082 uint32_t aligned_code_delta = aligned_offset - offset_;
1083 if (aligned_code_delta != 0) {
1084 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1085 ReportWriteFailure("code alignment padding", it);
1086 return false;
1087 }
1088 offset_ += aligned_code_delta;
1089 DCHECK_OFFSET_();
1090 }
1091 DCHECK_ALIGNED_PARAM(offset_,
1092 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1093 DCHECK_EQ(method_offsets.code_offset_,
1094 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1095 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1096 const OatQuickMethodHeader& method_header =
1097 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +00001098 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001099 ReportWriteFailure("method header", it);
1100 return false;
1101 }
1102 writer_->size_method_header_ += sizeof(method_header);
1103 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001104 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001105
1106 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001107 patched_code_.assign(quick_code.begin(), quick_code.end());
1108 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001109 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001110 uint32_t literal_offset = patch.LiteralOffset();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001111 if (patch.Type() == kLinkerPatchCallRelative) {
1112 // NOTE: Relative calls across oat files are not supported.
1113 uint32_t target_offset = GetTargetOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001114 writer_->relative_patcher_->PatchCall(&patched_code_,
1115 literal_offset,
1116 offset_ + literal_offset,
1117 target_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001118 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1119 uint32_t target_offset = GetDexCacheOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001120 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_,
1121 patch,
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001122 offset_ + literal_offset,
1123 target_offset);
1124 } else if (patch.Type() == kLinkerPatchCall) {
1125 uint32_t target_offset = GetTargetOffset(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001126 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001127 } else if (patch.Type() == kLinkerPatchMethod) {
1128 ArtMethod* method = GetTargetMethod(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001129 PatchMethodAddress(&patched_code_, literal_offset, method);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001130 } else if (patch.Type() == kLinkerPatchType) {
1131 mirror::Class* type = GetTargetType(patch);
Vladimir Marko944da602016-02-19 12:27:55 +00001132 PatchObjectAddress(&patched_code_, literal_offset, type);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001133 }
1134 }
1135 }
1136
Vladimir Marko49b0f452015-12-10 13:49:19 +00001137 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001138 ReportWriteFailure("method code", it);
1139 return false;
1140 }
1141 writer_->size_code_ += code_size;
1142 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001143 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001144 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001145 ++method_offsets_index_;
1146 }
1147
1148 return true;
1149 }
1150
1151 private:
1152 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001153 const size_t file_offset_;
1154 const ScopedObjectAccess soa_;
1155 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001156 ClassLinker* const class_linker_;
1157 mirror::DexCache* dex_cache_;
1158 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001159
1160 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1161 PLOG(ERROR) << "Failed to write " << what << " for "
1162 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1163 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001164
Mathieu Chartiere401d142015-04-22 13:56:20 -07001165 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001166 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001167 MethodReference ref = patch.TargetMethod();
1168 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001169 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1170 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001171 ArtMethod* method = dex_cache->GetResolvedMethod(
1172 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001173 CHECK(method != nullptr);
1174 return method;
1175 }
1176
Mathieu Chartier90443472015-07-16 20:32:27 -07001177 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001178 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1179 // If there's no new compiled code, either we're compiling an app and the target method
1180 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001181 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001182 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001183 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001184 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1185 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1186 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001187 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001188 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1189 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1190 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1191 target_offset = PointerToLowMemUInt32(oat_code_offset);
1192 } else {
1193 target_offset = target->IsNative()
1194 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1195 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1196 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001197 }
1198 return target_offset;
1199 }
1200
1201 mirror::Class* GetTargetType(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001202 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001203 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001204 ? dex_cache_ : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001205 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1206 CHECK(type != nullptr);
1207 return type;
1208 }
1209
Mathieu Chartier90443472015-07-16 20:32:27 -07001210 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001211 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001212 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1213 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1214 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1215 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001216 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001217 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001218 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1219 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001220 }
1221 }
1222
Vladimir Markof4da6752014-08-01 19:04:18 +01001223 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001224 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001225 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001226 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001227 } else {
1228 // NOTE: We're using linker patches for app->boot references when the image can
1229 // be relocated and therefore we need to emit .oat_patches. We're not using this
1230 // for app->app references, so check that the object is in the image space.
1231 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001232 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001233 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001234 uint32_t address = PointerToLowMemUInt32(object);
1235 DCHECK_LE(offset + 4, code->size());
1236 uint8_t* data = &(*code)[offset];
1237 data[0] = address & 0xffu;
1238 data[1] = (address >> 8) & 0xffu;
1239 data[2] = (address >> 16) & 0xffu;
1240 data[3] = (address >> 24) & 0xffu;
1241 }
1242
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001244 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001245 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001246 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001247 } else if (kIsDebugBuild) {
1248 // NOTE: We're using linker patches for app->boot references when the image can
1249 // be relocated and therefore we need to emit .oat_patches. We're not using this
1250 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001251 std::vector<gc::space::ImageSpace*> image_spaces =
1252 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1253 bool contains_method = false;
1254 for (gc::space::ImageSpace* image_space : image_spaces) {
1255 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1256 contains_method |=
1257 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1258 }
1259 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001260 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001261 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001262 uint32_t address = PointerToLowMemUInt32(method);
1263 DCHECK_LE(offset + 4, code->size());
1264 uint8_t* data = &(*code)[offset];
1265 data[0] = address & 0xffu;
1266 data[1] = (address >> 8) & 0xffu;
1267 data[2] = (address >> 16) & 0xffu;
1268 data[3] = (address >> 24) & 0xffu;
1269 }
1270
Vladimir Markof4da6752014-08-01 19:04:18 +01001271 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001272 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001273 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001274 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001275 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1276 // TODO: Clean up offset types.
1277 // The target_offset must be treated as signed for cross-oat patching.
1278 const void* target = reinterpret_cast<const void*>(
1279 writer_->image_writer_->GetOatDataBegin(oat_index) +
1280 static_cast<int32_t>(target_offset));
1281 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001282 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001283 DCHECK_LE(offset + 4, code->size());
1284 uint8_t* data = &(*code)[offset];
1285 data[0] = address & 0xffu;
1286 data[1] = (address >> 8) & 0xffu;
1287 data[2] = (address >> 16) & 0xffu;
1288 data[3] = (address >> 24) & 0xffu;
1289 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001290};
1291
1292template <typename DataAccess>
1293class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1294 public:
1295 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001296 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297 : OatDexMethodVisitor(writer, relative_offset),
1298 out_(out),
1299 file_offset_(file_offset) {
1300 }
1301
1302 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001303 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001304 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1305
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001306 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001307 size_t file_offset = file_offset_;
1308 OutputStream* out = out_;
1309
1310 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1311 ++method_offsets_index_;
1312
1313 // Write deduplicated map.
Vladimir Marko35831e82015-09-11 11:59:18 +01001314 ArrayRef<const uint8_t> map = DataAccess::GetData(compiled_method);
1315 size_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001316 DCHECK((map_size == 0u && map_offset == 0u) ||
1317 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001318 << map_size << " " << map_offset << " " << offset_ << " "
1319 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001320 if (map_size != 0u && map_offset == offset_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001321 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001322 ReportWriteFailure(it);
1323 return false;
1324 }
1325 offset_ += map_size;
1326 }
1327 DCHECK_OFFSET_();
1328 }
1329
1330 return true;
1331 }
1332
1333 private:
1334 OutputStream* const out_;
1335 size_t const file_offset_;
1336
1337 void ReportWriteFailure(const ClassDataItemIterator& it) {
1338 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1339 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1340 }
1341};
1342
1343// Visit all methods from all classes in all dex files with the specified visitor.
1344bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1345 for (const DexFile* dex_file : *dex_files_) {
1346 const size_t class_def_count = dex_file->NumClassDefs();
1347 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1348 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1349 return false;
1350 }
1351 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001352 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001353 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001354 ClassDataItemIterator it(*dex_file, class_data);
1355 while (it.HasNextStaticField()) {
1356 it.Next();
1357 }
1358 while (it.HasNextInstanceField()) {
1359 it.Next();
1360 }
1361 size_t class_def_method_index = 0u;
1362 while (it.HasNextDirectMethod()) {
1363 if (!visitor->VisitMethod(class_def_method_index, it)) {
1364 return false;
1365 }
1366 ++class_def_method_index;
1367 it.Next();
1368 }
1369 while (it.HasNextVirtualMethod()) {
1370 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1371 return false;
1372 }
1373 ++class_def_method_index;
1374 it.Next();
1375 }
1376 }
1377 if (UNLIKELY(!visitor->EndClass())) {
1378 return false;
1379 }
1380 }
1381 }
1382 return true;
1383}
1384
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001385size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1386 const InstructionSetFeatures* instruction_set_features,
1387 uint32_t num_dex_files,
1388 SafeMap<std::string, std::string>* key_value_store) {
1389 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1390 oat_header_.reset(OatHeader::Create(instruction_set,
1391 instruction_set_features,
1392 num_dex_files,
1393 key_value_store));
1394 size_oat_header_ += sizeof(OatHeader);
1395 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001396 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001397}
1398
1399size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001400 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1401 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001402 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001403 oat_dex_file.offset_ = offset;
1404 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001405 }
1406 return offset;
1407}
1408
Brian Carlstrom389efb02012-01-11 12:06:26 -08001409size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001410 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001411 InitOatClassesMethodVisitor visitor(this, offset);
1412 bool success = VisitDexMethods(&visitor);
1413 CHECK(success);
1414 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001415
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001416 // Update oat_dex_files_.
1417 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001418 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1419 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001421 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001422 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001423 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001424 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001425 CHECK(oat_class_it == oat_classes_.end());
1426
1427 return offset;
1428}
1429
1430size_t OatWriter::InitOatMaps(size_t offset) {
1431 #define VISIT(VisitorType) \
1432 do { \
1433 VisitorType visitor(this, offset); \
1434 bool success = VisitDexMethods(&visitor); \
1435 DCHECK(success); \
1436 offset = visitor.GetOffset(); \
1437 } while (false)
1438
1439 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1440 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1441 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1442
1443 #undef VISIT
1444
Brian Carlstrome24fa612011-09-29 00:53:55 -07001445 return offset;
1446}
1447
1448size_t OatWriter::InitOatCode(size_t offset) {
1449 // calculate the offsets within OatHeader to executable code
1450 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001451 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001452 // required to be on a new page boundary
1453 offset = RoundUp(offset, kPageSize);
1454 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001455 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001456 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001457 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001458
Ian Rogers848871b2013-08-05 10:56:33 -07001459 #define DO_TRAMPOLINE(field, fn_name) \
1460 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001461 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1462 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001463 field.reset(compiler_driver_->Create ## fn_name()); \
1464 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465
Ian Rogers848871b2013-08-05 10:56:33 -07001466 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001467 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001468 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001469 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1470 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001471
Ian Rogers848871b2013-08-05 10:56:33 -07001472 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001473 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001474 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1475 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1476 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001477 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001478 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001479 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001480 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001481 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001482 return offset;
1483}
1484
1485size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001486 #define VISIT(VisitorType) \
1487 do { \
1488 VisitorType visitor(this, offset); \
1489 bool success = VisitDexMethods(&visitor); \
1490 DCHECK(success); \
1491 offset = visitor.GetOffset(); \
1492 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001493
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001494 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001495 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001496 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001497 }
Logan Chien8b977d32012-02-21 19:14:55 +08001498
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001499 #undef VISIT
1500
Brian Carlstrome24fa612011-09-29 00:53:55 -07001501 return offset;
1502}
1503
David Srbeckybc90fd02015-04-22 19:40:27 +01001504bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001505 CHECK(write_state_ == WriteState::kWriteRoData);
1506
1507 if (!WriteClassOffsets(out)) {
1508 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001509 return false;
1510 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001511
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001512 if (!WriteClasses(out)) {
1513 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001514 return false;
1515 }
1516
Vladimir Markof4da6752014-08-01 19:04:18 +01001517 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001518 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001519 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1520 return false;
1521 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001522 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001523 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001524 relative_offset = WriteMaps(out, file_offset, relative_offset);
1525 if (relative_offset == 0) {
1526 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1527 return false;
1528 }
1529
David Srbeckybc90fd02015-04-22 19:40:27 +01001530 // Write padding.
1531 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1532 relative_offset += size_executable_offset_alignment_;
1533 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1534 size_t expected_file_offset = file_offset + relative_offset;
1535 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1536 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1537 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1538 return 0;
1539 }
1540 DCHECK_OFFSET();
1541
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001542 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001543 return true;
1544}
1545
1546bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001547 CHECK(write_state_ == WriteState::kWriteText);
1548
Vladimir Marko944da602016-02-19 12:27:55 +00001549 SetMultiOatRelativePatcherAdjustment();
1550
David Srbeckybc90fd02015-04-22 19:40:27 +01001551 const size_t file_offset = oat_data_offset_;
1552 size_t relative_offset = oat_header_->GetExecutableOffset();
1553 DCHECK_OFFSET();
1554
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001555 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001556 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001557 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001558 return false;
1559 }
1560
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001561 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1562 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001563 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001564 return false;
1565 }
1566
Vladimir Markof4da6752014-08-01 19:04:18 +01001567 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001568 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1570 return false;
1571 }
1572
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001573 if (kIsDebugBuild) {
1574 uint32_t size_total = 0;
1575 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001576 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001577 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001578
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001579 DO_STAT(size_dex_file_alignment_);
1580 DO_STAT(size_executable_offset_alignment_);
1581 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001582 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001583 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001584 DO_STAT(size_interpreter_to_interpreter_bridge_);
1585 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1586 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001587 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001588 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001589 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001590 DO_STAT(size_quick_to_interpreter_bridge_);
1591 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001592 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001593 DO_STAT(size_code_);
1594 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001595 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001596 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001597 DO_STAT(size_mapping_table_);
1598 DO_STAT(size_vmap_table_);
1599 DO_STAT(size_gc_map_);
1600 DO_STAT(size_oat_dex_file_location_size_);
1601 DO_STAT(size_oat_dex_file_location_data_);
1602 DO_STAT(size_oat_dex_file_location_checksum_);
1603 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001604 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001605 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001606 DO_STAT(size_oat_lookup_table_alignment_);
1607 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001608 DO_STAT(size_oat_class_offsets_alignment_);
1609 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001610 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001611 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001612 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001613 DO_STAT(size_oat_class_method_offsets_);
1614 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001615
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001616 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001617 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001618 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001619 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001620
Vladimir Markof4da6752014-08-01 19:04:18 +01001621 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001622 CHECK_EQ(size_, relative_offset);
1623
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001624 write_state_ = WriteState::kWriteHeader;
1625 return true;
1626}
1627
1628bool OatWriter::WriteHeader(OutputStream* out,
1629 uint32_t image_file_location_oat_checksum,
1630 uintptr_t image_file_location_oat_begin,
1631 int32_t image_patch_delta) {
1632 CHECK(write_state_ == WriteState::kWriteHeader);
1633
1634 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1635 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1636 if (compiler_driver_->IsBootImage()) {
1637 CHECK_EQ(image_patch_delta, 0);
1638 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1639 } else {
1640 CHECK_ALIGNED(image_patch_delta, kPageSize);
1641 oat_header_->SetImagePatchDelta(image_patch_delta);
1642 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001643 oat_header_->UpdateChecksumWithHeaderData();
1644
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001645 const size_t file_offset = oat_data_offset_;
1646
1647 off_t current_offset = out->Seek(0, kSeekCurrent);
1648 if (current_offset == static_cast<off_t>(-1)) {
1649 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1650 return false;
1651 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001652 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001653 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1654 return false;
1655 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001656 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001657
1658 // Flush all other data before writing the header.
1659 if (!out->Flush()) {
1660 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1661 return false;
1662 }
1663 // Write the header.
1664 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001665 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001666 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1667 return false;
1668 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001669 // Flush the header data.
1670 if (!out->Flush()) {
1671 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001672 return false;
1673 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001674
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001675 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1676 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1677 return false;
1678 }
1679 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1680
1681 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001682 return true;
1683}
1684
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685bool OatWriter::WriteClassOffsets(OutputStream* out) {
1686 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1687 if (oat_dex_file.class_offsets_offset_ != 0u) {
1688 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1689 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1690 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1691 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1692 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001693 return false;
1694 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001695 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1696 return false;
1697 }
1698 }
1699 }
1700 return true;
1701}
1702
1703bool OatWriter::WriteClasses(OutputStream* out) {
1704 for (OatClass& oat_class : oat_classes_) {
1705 if (!oat_class.Write(this, out, oat_data_offset_)) {
1706 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1707 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001708 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001709 }
1710 return true;
1711}
1712
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001713size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1714 #define VISIT(VisitorType) \
1715 do { \
1716 VisitorType visitor(this, out, file_offset, relative_offset); \
1717 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1718 return 0; \
1719 } \
1720 relative_offset = visitor.GetOffset(); \
1721 } while (false)
1722
1723 size_t gc_maps_offset = relative_offset;
1724 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1725 size_gc_map_ = relative_offset - gc_maps_offset;
1726
1727 size_t mapping_tables_offset = relative_offset;
1728 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1729 size_mapping_table_ = relative_offset - mapping_tables_offset;
1730
1731 size_t vmap_tables_offset = relative_offset;
1732 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1733 size_vmap_table_ = relative_offset - vmap_tables_offset;
1734
1735 #undef VISIT
1736
1737 return relative_offset;
1738}
1739
1740size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001741 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001742 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001743
Ian Rogers848871b2013-08-05 10:56:33 -07001744 #define DO_TRAMPOLINE(field) \
1745 do { \
1746 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1747 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001748 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001749 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001750 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001751 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001752 return false; \
1753 } \
1754 size_ ## field += field->size(); \
1755 relative_offset += alignment_padding + field->size(); \
1756 DCHECK_OFFSET(); \
1757 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001758
Ian Rogers848871b2013-08-05 10:56:33 -07001759 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001760 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001761 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001762 DO_TRAMPOLINE(quick_resolution_trampoline_);
1763 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1764 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001765 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001766 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001767}
1768
Ian Rogers3d504072014-03-01 09:16:49 -08001769size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001770 const size_t file_offset,
1771 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001772 #define VISIT(VisitorType) \
1773 do { \
1774 VisitorType visitor(this, out, file_offset, relative_offset); \
1775 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1776 return 0; \
1777 } \
1778 relative_offset = visitor.GetOffset(); \
1779 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001780
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001781 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001782
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001783 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001784
Vladimir Markob163bb72015-03-31 21:49:49 +01001785 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1786 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1787 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1788
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001789 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001790}
1791
Vladimir Marko944da602016-02-19 12:27:55 +00001792bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001793 // Get the elf file offset of the oat file.
1794 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1795 if (raw_file_offset == static_cast<off_t>(-1)) {
1796 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1797 return false;
1798 }
1799 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1800 return true;
1801}
1802
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001803bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1804 // Read the dex file header and perform minimal verification.
1805 uint8_t raw_header[sizeof(DexFile::Header)];
1806 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1807 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1808 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1809 return false;
1810 }
1811 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1812 return false;
1813 }
1814
1815 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1816 oat_dex_file->dex_file_size_ = header->file_size_;
1817 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1818 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1819 return true;
1820}
1821
1822bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1823 if (!DexFile::IsMagicValid(raw_header)) {
1824 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1825 return false;
1826 }
1827 if (!DexFile::IsVersionValid(raw_header)) {
1828 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1829 return false;
1830 }
1831 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1832 if (header->file_size_ < sizeof(DexFile::Header)) {
1833 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1834 << " File: " << location;
1835 return false;
1836 }
1837 return true;
1838}
1839
1840bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1841 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1842
1843 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001844 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001845 return false;
1846 }
1847
1848 // Write dex files.
1849 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1850 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1851 return false;
1852 }
1853 }
1854
1855 // Close sources.
1856 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1857 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1858 }
1859 zipped_dex_files_.clear();
1860 zip_archives_.clear();
1861 raw_dex_files_.clear();
1862 return true;
1863}
1864
1865bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1866 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1867 return false;
1868 }
1869 if (oat_dex_file->source_.IsZipEntry()) {
1870 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1871 return false;
1872 }
1873 } else if (oat_dex_file->source_.IsRawFile()) {
1874 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1875 return false;
1876 }
1877 } else {
1878 DCHECK(oat_dex_file->source_.IsRawData());
1879 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1880 return false;
1881 }
1882 }
1883
1884 // Update current size and account for the written data.
1885 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1886 size_ += oat_dex_file->dex_file_size_;
1887 size_dex_file_ += oat_dex_file->dex_file_size_;
1888 return true;
1889}
1890
1891bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1892 // Dex files are required to be 4 byte aligned.
1893 size_t original_offset = size_;
1894 size_t offset = RoundUp(original_offset, 4);
1895 size_dex_file_alignment_ += offset - original_offset;
1896
1897 // Seek to the start of the dex file and flush any pending operations in the stream.
1898 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1899 uint32_t start_offset = oat_data_offset_ + offset;
1900 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1901 if (actual_offset != static_cast<off_t>(start_offset)) {
1902 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1903 << " Expected: " << start_offset
1904 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1905 return false;
1906 }
1907 if (!out->Flush()) {
1908 PLOG(ERROR) << "Failed to flush before writing dex file."
1909 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1910 return false;
1911 }
1912 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1913 if (actual_offset != static_cast<off_t>(start_offset)) {
1914 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1915 << " Expected: " << start_offset
1916 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1917 return false;
1918 }
1919
1920 size_ = offset;
1921 oat_dex_file->dex_file_offset_ = offset;
1922 return true;
1923}
1924
1925bool OatWriter::WriteDexFile(OutputStream* rodata,
1926 File* file,
1927 OatDexFile* oat_dex_file,
1928 ZipEntry* dex_file) {
1929 size_t start_offset = oat_data_offset_ + size_;
1930 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1931
1932 // Extract the dex file and get the extracted size.
1933 std::string error_msg;
1934 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1935 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1936 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1937 return false;
1938 }
1939 if (file->Flush() != 0) {
1940 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1941 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1942 return false;
1943 }
1944 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1945 if (extracted_end == static_cast<off_t>(-1)) {
1946 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1947 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1948 return false;
1949 }
1950 if (extracted_end < static_cast<off_t>(start_offset)) {
1951 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1952 << " Start: " << start_offset
1953 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1954 return false;
1955 }
1956 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1957 if (extracted_size < sizeof(DexFile::Header)) {
1958 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1959 << extracted_size << " File: " << oat_dex_file->GetLocation();
1960 return false;
1961 }
1962
1963 // Read the dex file header and extract required data to OatDexFile.
1964 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1965 if (actual_offset != static_cast<off_t>(start_offset)) {
1966 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1967 << " Expected: " << start_offset
1968 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1969 return false;
1970 }
1971 if (!ReadDexFileHeader(file, oat_dex_file)) {
1972 return false;
1973 }
1974 if (extracted_size < oat_dex_file->dex_file_size_) {
1975 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1976 << " file size from header: " << oat_dex_file->dex_file_size_
1977 << " File: " << oat_dex_file->GetLocation();
1978 return false;
1979 }
1980
1981 // Override the checksum from header with the CRC from ZIP entry.
1982 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1983
1984 // Seek both file and stream to the end offset.
1985 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1986 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1987 if (actual_offset != static_cast<off_t>(end_offset)) {
1988 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1989 << " Expected: " << end_offset
1990 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1991 return false;
1992 }
1993 actual_offset = rodata->Seek(end_offset, kSeekSet);
1994 if (actual_offset != static_cast<off_t>(end_offset)) {
1995 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1996 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1997 return false;
1998 }
1999 if (!rodata->Flush()) {
2000 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2001 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2002 return false;
2003 }
2004
2005 // If we extracted more than the size specified in the header, truncate the file.
2006 if (extracted_size > oat_dex_file->dex_file_size_) {
2007 if (file->SetLength(end_offset) != 0) {
2008 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2009 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2010 return false;
2011 }
2012 }
2013
2014 return true;
2015}
2016
2017bool OatWriter::WriteDexFile(OutputStream* rodata,
2018 File* file,
2019 OatDexFile* oat_dex_file,
2020 File* dex_file) {
2021 size_t start_offset = oat_data_offset_ + size_;
2022 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2023
2024 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2025 if (input_offset != static_cast<off_t>(0)) {
2026 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2027 << " Expected: 0"
2028 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2029 return false;
2030 }
2031 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2032 return false;
2033 }
2034
2035 // Copy the input dex file using sendfile().
2036 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2037 PLOG(ERROR) << "Failed to copy dex file to oat file."
2038 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2039 return false;
2040 }
2041 if (file->Flush() != 0) {
2042 PLOG(ERROR) << "Failed to flush dex file."
2043 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2044 return false;
2045 }
2046
2047 // Check file position and seek the stream to the end offset.
2048 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2049 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2050 if (actual_offset != static_cast<off_t>(end_offset)) {
2051 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2052 << " Expected: " << end_offset
2053 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2054 return false;
2055 }
2056 actual_offset = rodata->Seek(end_offset, kSeekSet);
2057 if (actual_offset != static_cast<off_t>(end_offset)) {
2058 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2059 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2060 return false;
2061 }
2062 if (!rodata->Flush()) {
2063 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2064 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2065 return false;
2066 }
2067
2068 return true;
2069}
2070
2071bool OatWriter::WriteDexFile(OutputStream* rodata,
2072 OatDexFile* oat_dex_file,
2073 const uint8_t* dex_file) {
2074 // Note: The raw data has already been checked to contain the header
2075 // and all the data that the header specifies as the file size.
2076 DCHECK(dex_file != nullptr);
2077 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2078 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2079
2080 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2081 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2082 << " to " << rodata->GetLocation();
2083 return false;
2084 }
2085 if (!rodata->Flush()) {
2086 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2087 << " File: " << oat_dex_file->GetLocation();
2088 return false;
2089 }
2090
2091 // Update dex file size and resize class offsets in the OatDexFile.
2092 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2093 oat_dex_file->dex_file_size_ = header->file_size_;
2094 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2095 return true;
2096}
2097
2098bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2099 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2100
2101 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2102 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2103 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2104 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2105 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2106 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2107 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2108 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2109 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2110 return false;
2111 }
2112
2113 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2114 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2115
2116 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2117 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2118
2119 // Write OatDexFile.
2120 if (!oat_dex_file->Write(this, rodata)) {
2121 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2122 return false;
2123 }
2124 }
2125
2126 return true;
2127}
2128
2129bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2130 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2131
2132 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2133 if (file->SetLength(new_length) != 0) {
2134 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2135 << "File: " << file->GetPath();
2136 return false;
2137 }
2138 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2139 if (actual_offset != static_cast<off_t>(new_length)) {
2140 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2141 << " Actual: " << actual_offset << " Expected: " << new_length
2142 << " File: " << rodata->GetLocation();
2143 return false;
2144 }
2145 if (!rodata->Flush()) {
2146 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2147 << " File: " << rodata->GetLocation();
2148 return false;
2149 }
2150 return true;
2151}
2152
2153bool OatWriter::OpenDexFiles(
2154 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002155 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002156 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2157 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2158 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2159
2160 if (oat_dex_files_.empty()) {
2161 // Nothing to do.
2162 return true;
2163 }
2164
2165 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2166 size_t length = size_ - map_offset;
2167 std::string error_msg;
2168 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2169 PROT_READ | PROT_WRITE,
2170 MAP_SHARED,
2171 file->Fd(),
2172 oat_data_offset_ + map_offset,
2173 /* low_4gb */ false,
2174 file->GetPath().c_str(),
2175 &error_msg));
2176 if (dex_files_map == nullptr) {
2177 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2178 << " error: " << error_msg;
2179 return false;
2180 }
2181 std::vector<std::unique_ptr<const DexFile>> dex_files;
2182 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2183 // Make sure no one messed with input files while we were copying data.
2184 // At the very least we need consistent file size and number of class definitions.
2185 const uint8_t* raw_dex_file =
2186 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2187 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2188 // Note: ValidateDexFileHeader() already logged an error message.
2189 LOG(ERROR) << "Failed to verify written dex file header!"
2190 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2191 << " ~ " << static_cast<const void*>(raw_dex_file);
2192 return false;
2193 }
2194 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2195 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2196 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2197 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2198 << " Output: " << file->GetPath();
2199 return false;
2200 }
2201 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2202 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2203 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2204 << " Output: " << file->GetPath();
2205 return false;
2206 }
2207
2208 // Now, open the dex file.
2209 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2210 oat_dex_file.dex_file_size_,
2211 oat_dex_file.GetLocation(),
2212 oat_dex_file.dex_file_location_checksum_,
2213 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002214 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002215 &error_msg));
2216 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002217 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2218 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002219 return false;
2220 }
2221 }
2222
2223 *opened_dex_files_map = std::move(dex_files_map);
2224 *opened_dex_files = std::move(dex_files);
2225 return true;
2226}
2227
2228bool OatWriter::WriteTypeLookupTables(
2229 MemMap* opened_dex_files_map,
2230 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2231 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2232
2233 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2234 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2235 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2236 if (oat_dex_file->lookup_table_offset_ != 0u) {
2237 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2238 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2239 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2240 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2241 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2242 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2243 }
2244 }
2245
2246 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2247 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2248 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2249 return false;
2250 }
2251
2252 return true;
2253}
2254
Vladimir Markof4da6752014-08-01 19:04:18 +01002255bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2256 static const uint8_t kPadding[] = {
2257 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2258 };
2259 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2260 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2261 return false;
2262 }
2263 size_code_alignment_ += aligned_code_delta;
2264 return true;
2265}
2266
Vladimir Marko49b0f452015-12-10 13:49:19 +00002267bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2268 oat_header_->UpdateChecksum(data, size);
2269 return out->WriteFully(data, size);
2270}
2271
Vladimir Marko944da602016-02-19 12:27:55 +00002272void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2273 DCHECK(dex_files_ != nullptr);
2274 DCHECK(relative_patcher_ != nullptr);
2275 DCHECK_NE(oat_data_offset_, 0u);
2276 if (image_writer_ != nullptr && !dex_files_->empty()) {
2277 // The oat data begin may not be initialized yet but the oat file offset is ready.
2278 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2279 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2280 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002281 }
2282}
2283
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002284OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2285 DexFileSource source,
2286 CreateTypeLookupTable create_type_lookup_table)
2287 : source_(source),
2288 create_type_lookup_table_(create_type_lookup_table),
2289 dex_file_size_(0),
2290 offset_(0),
2291 dex_file_location_size_(strlen(dex_file_location)),
2292 dex_file_location_data_(dex_file_location),
2293 dex_file_location_checksum_(0u),
2294 dex_file_offset_(0u),
2295 class_offsets_offset_(0u),
2296 lookup_table_offset_(0u),
2297 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002298}
2299
2300size_t OatWriter::OatDexFile::SizeOf() const {
2301 return sizeof(dex_file_location_size_)
2302 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002303 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002304 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002305 + sizeof(class_offsets_offset_)
2306 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002307}
2308
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002309void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2310 DCHECK_EQ(lookup_table_offset_, 0u);
2311 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2312 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2313 if (table_size != 0u) {
2314 // Type tables are required to be 4 byte aligned.
2315 size_t original_offset = oat_writer->size_;
2316 size_t offset = RoundUp(original_offset, 4);
2317 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2318 lookup_table_offset_ = offset;
2319 oat_writer->size_ = offset + table_size;
2320 oat_writer->size_oat_lookup_table_ += table_size;
2321 }
2322 }
2323}
2324
2325void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2326 DCHECK_EQ(class_offsets_offset_, 0u);
2327 if (!class_offsets_.empty()) {
2328 // Class offsets are required to be 4 byte aligned.
2329 size_t original_offset = oat_writer->size_;
2330 size_t offset = RoundUp(original_offset, 4);
2331 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2332 class_offsets_offset_ = offset;
2333 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2334 }
2335}
2336
2337bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2338 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002339 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002340
Vladimir Marko49b0f452015-12-10 13:49:19 +00002341 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002342 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002343 return false;
2344 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002345 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002346
Vladimir Marko49b0f452015-12-10 13:49:19 +00002347 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002348 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002349 return false;
2350 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002351 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002352
Vladimir Marko49b0f452015-12-10 13:49:19 +00002353 if (!oat_writer->WriteData(out,
2354 &dex_file_location_checksum_,
2355 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002356 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002357 return false;
2358 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002359 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002360
Vladimir Marko49b0f452015-12-10 13:49:19 +00002361 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002362 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002363 return false;
2364 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002365 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002366
2367 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2368 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2369 return false;
2370 }
2371 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2372
Vladimir Marko49b0f452015-12-10 13:49:19 +00002373 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002374 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2375 return false;
2376 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002377 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002378
2379 return true;
2380}
2381
2382bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002383 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002384 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2385 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002386 return false;
2387 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002388 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002389 return true;
2390}
2391
Brian Carlstromba150c32013-08-27 17:31:03 -07002392OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002393 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002394 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002395 mirror::Class::Status status)
2396 : compiled_methods_(compiled_methods) {
2397 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002398 CHECK_LE(num_non_null_compiled_methods, num_methods);
2399
Brian Carlstrom265091e2013-01-30 14:08:26 -08002400 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002401 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2402
2403 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2404 // apply when there are 0 methods, we just arbitrarily say that 0
2405 // methods means kOatClassNoneCompiled and that we won't use
2406 // kOatClassAllCompiled unless there is at least one compiled
2407 // method. This means in an interpretter only system, we can assert
2408 // that all classes are kOatClassNoneCompiled.
2409 if (num_non_null_compiled_methods == 0) {
2410 type_ = kOatClassNoneCompiled;
2411 } else if (num_non_null_compiled_methods == num_methods) {
2412 type_ = kOatClassAllCompiled;
2413 } else {
2414 type_ = kOatClassSomeCompiled;
2415 }
2416
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002417 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002418 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002419 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002420
2421 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2422 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002423 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002424 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2425 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2426 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2427 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002428 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002429 method_bitmap_size_ = 0;
2430 }
2431
2432 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002433 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002434 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002435 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2436 } else {
2437 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2438 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2439 if (type_ == kOatClassSomeCompiled) {
2440 method_bitmap_->SetBit(i);
2441 }
2442 }
2443 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002444}
2445
Brian Carlstrom265091e2013-01-30 14:08:26 -08002446size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2447 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002448 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2449 if (method_offset == 0) {
2450 return 0;
2451 }
2452 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002453}
2454
2455size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2456 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002457 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002458}
2459
2460size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002461 return sizeof(status_)
2462 + sizeof(type_)
2463 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2464 + method_bitmap_size_
2465 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002466}
2467
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002468bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002469 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002470 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002471 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002472 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002473 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002474 return false;
2475 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002476 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002477
2478 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002479 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002480 return false;
2481 }
2482 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002483
Brian Carlstromba150c32013-08-27 17:31:03 -07002484 if (method_bitmap_size_ != 0) {
2485 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002486 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002487 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002488 return false;
2489 }
2490 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002491
2492 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002493 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002494 return false;
2495 }
2496 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2497 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002498
2499 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002500 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002501 return false;
2502 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002503 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002504 return true;
2505}
2506
Brian Carlstrome24fa612011-09-29 00:53:55 -07002507} // namespace art