blob: e804beef0dfb9da48c4a02bea497b49f1528d09d [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_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700279 size_oat_dex_file_location_size_(0),
280 size_oat_dex_file_location_data_(0),
281 size_oat_dex_file_location_checksum_(0),
282 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000283 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000284 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000285 size_oat_lookup_table_alignment_(0),
286 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000287 size_oat_class_offsets_alignment_(0),
288 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700289 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700290 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700291 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100292 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000293 relative_patcher_(nullptr),
294 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000295}
296
297bool OatWriter::AddDexFileSource(const char* filename,
298 const char* location,
299 CreateTypeLookupTable create_type_lookup_table) {
300 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
301 uint32_t magic;
302 std::string error_msg;
303 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
304 if (fd.get() == -1) {
305 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
306 return false;
307 } else if (IsDexMagic(magic)) {
308 // The file is open for reading, not writing, so it's OK to let the File destructor
309 // close it without checking for explicit Close(), so pass checkUsage = false.
310 raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
311 oat_dex_files_.emplace_back(location,
312 DexFileSource(raw_dex_files_.back().get()),
313 create_type_lookup_table);
314 } else if (IsZipMagic(magic)) {
315 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
316 return false;
317 }
318 } else {
319 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
320 return false;
321 }
322 return true;
323}
324
325// Add dex file source(s) from a zip file specified by a file handle.
326bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
327 const char* location,
328 CreateTypeLookupTable create_type_lookup_table) {
329 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
330 std::string error_msg;
331 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
332 ZipArchive* zip_archive = zip_archives_.back().get();
333 if (zip_archive == nullptr) {
334 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
335 << error_msg;
336 return false;
337 }
338 for (size_t i = 0; ; ++i) {
339 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
340 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
341 if (entry == nullptr) {
342 break;
343 }
344 zipped_dex_files_.push_back(std::move(entry));
345 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
346 const char* full_location = zipped_dex_file_locations_.back().c_str();
347 oat_dex_files_.emplace_back(full_location,
348 DexFileSource(zipped_dex_files_.back().get()),
349 create_type_lookup_table);
350 }
351 if (zipped_dex_file_locations_.empty()) {
352 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
353 return false;
354 }
355 return true;
356}
357
358// Add dex file source from raw memory.
359bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
360 const char* location,
361 uint32_t location_checksum,
362 CreateTypeLookupTable create_type_lookup_table) {
363 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
364 if (data.size() < sizeof(DexFile::Header)) {
365 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
366 << data.size() << " File: " << location;
367 return false;
368 }
369 if (!ValidateDexFileHeader(data.data(), location)) {
370 return false;
371 }
372 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
373 if (data.size() < header->file_size_) {
374 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
375 << " file size from header: " << header->file_size_ << " File: " << location;
376 return false;
377 }
378
379 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
380 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
381 return true;
382}
383
384dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
385 dchecked_vector<const char*> locations;
386 locations.reserve(oat_dex_files_.size());
387 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
388 locations.push_back(oat_dex_file.GetLocation());
389 }
390 return locations;
391}
392
393bool OatWriter::WriteAndOpenDexFiles(
394 OutputStream* rodata,
395 File* file,
396 InstructionSet instruction_set,
397 const InstructionSetFeatures* instruction_set_features,
398 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800399 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000400 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
401 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
402 CHECK(write_state_ == WriteState::kAddingDexFileSources);
403
404 size_t offset = InitOatHeader(instruction_set,
405 instruction_set_features,
406 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
407 key_value_store);
408 offset = InitOatDexFiles(offset);
409 size_ = offset;
410
411 std::unique_ptr<MemMap> dex_files_map;
412 std::vector<std::unique_ptr<const DexFile>> dex_files;
413 if (!WriteDexFiles(rodata, file)) {
414 return false;
415 }
416 // Reserve space for type lookup tables and update type_lookup_table_offset_.
417 for (OatDexFile& oat_dex_file : oat_dex_files_) {
418 oat_dex_file.ReserveTypeLookupTable(this);
419 }
420 size_t size_after_type_lookup_tables = size_;
421 // Reserve space for class offsets and update class_offsets_offset_.
422 for (OatDexFile& oat_dex_file : oat_dex_files_) {
423 oat_dex_file.ReserveClassOffsets(this);
424 }
425 if (!WriteOatDexFiles(rodata) ||
426 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800427 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000428 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
429 return false;
430 }
431
432 *opened_dex_files_map = std::move(dex_files_map);
433 *opened_dex_files = std::move(dex_files);
434 write_state_ = WriteState::kPrepareLayout;
435 return true;
436}
437
438void OatWriter::PrepareLayout(const CompilerDriver* compiler,
439 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000440 const std::vector<const DexFile*>& dex_files,
441 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000442 CHECK(write_state_ == WriteState::kPrepareLayout);
443
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 compiler_driver_ = compiler;
445 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000446 dex_files_ = &dex_files;
447 relative_patcher_ = relative_patcher;
448 SetMultiOatRelativePatcherAdjustment();
449
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000450 if (compiling_boot_image_) {
451 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800452 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100453 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000454 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100455
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000456 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800457 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000458 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800459 offset = InitOatClasses(offset);
460 }
461 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000462 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100463 offset = InitOatMaps(offset);
464 }
465 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000466 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800467 offset = InitOatCode(offset);
468 }
469 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000470 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800471 offset = InitOatCodeDexFiles(offset);
472 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700473 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700474
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800475 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100476 // Allocate space for app dex cache arrays in the .bss section.
477 size_t bss_start = RoundUp(size_, kPageSize);
478 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
479 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100481 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
482 DexCacheArraysLayout layout(pointer_size, dex_file);
483 bss_size_ += layout.Size();
484 }
485 }
486
Brian Carlstrome24fa612011-09-29 00:53:55 -0700487 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800488 if (compiling_boot_image_) {
489 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800491 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492
493 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700494}
495
Ian Rogers0571d352011-11-03 19:51:38 -0700496OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700497}
498
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100499class OatWriter::DexMethodVisitor {
500 public:
501 DexMethodVisitor(OatWriter* writer, size_t offset)
502 : writer_(writer),
503 offset_(offset),
504 dex_file_(nullptr),
505 class_def_index_(DexFile::kDexNoIndex) {
506 }
507
508 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
509 DCHECK(dex_file_ == nullptr);
510 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
511 dex_file_ = dex_file;
512 class_def_index_ = class_def_index;
513 return true;
514 }
515
516 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
517
518 virtual bool EndClass() {
519 if (kIsDebugBuild) {
520 dex_file_ = nullptr;
521 class_def_index_ = DexFile::kDexNoIndex;
522 }
523 return true;
524 }
525
526 size_t GetOffset() const {
527 return offset_;
528 }
529
530 protected:
531 virtual ~DexMethodVisitor() { }
532
533 OatWriter* const writer_;
534
535 // The offset is usually advanced for each visited method by the derived class.
536 size_t offset_;
537
538 // The dex file and class def index are set in StartClass().
539 const DexFile* dex_file_;
540 size_t class_def_index_;
541};
542
543class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
544 public:
545 OatDexMethodVisitor(OatWriter* writer, size_t offset)
546 : DexMethodVisitor(writer, offset),
547 oat_class_index_(0u),
548 method_offsets_index_(0u) {
549 }
550
551 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
552 DexMethodVisitor::StartClass(dex_file, class_def_index);
553 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
554 method_offsets_index_ = 0u;
555 return true;
556 }
557
558 bool EndClass() {
559 ++oat_class_index_;
560 return DexMethodVisitor::EndClass();
561 }
562
563 protected:
564 size_t oat_class_index_;
565 size_t method_offsets_index_;
566};
567
568class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
569 public:
570 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
571 : DexMethodVisitor(writer, offset),
572 compiled_methods_(),
573 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000574 size_t num_classes = 0u;
575 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
576 num_classes += oat_dex_file.class_offsets_.size();
577 }
578 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100579 compiled_methods_.reserve(256u);
580 }
581
582 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
583 DexMethodVisitor::StartClass(dex_file, class_def_index);
584 compiled_methods_.clear();
585 num_non_null_compiled_methods_ = 0u;
586 return true;
587 }
588
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300589 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
590 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100591 // Fill in the compiled_methods_ array for methods that have a
592 // CompiledMethod. We track the number of non-null entries in
593 // num_non_null_compiled_methods_ since we only want to allocate
594 // OatMethodOffsets for the compiled methods.
595 uint32_t method_idx = it.GetMemberIndex();
596 CompiledMethod* compiled_method =
597 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
598 compiled_methods_.push_back(compiled_method);
599 if (compiled_method != nullptr) {
600 ++num_non_null_compiled_methods_;
601 }
602 return true;
603 }
604
605 bool EndClass() {
606 ClassReference class_ref(dex_file_, class_def_index_);
607 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
608 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700609 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100610 status = compiled_class->GetStatus();
611 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
612 status = mirror::Class::kStatusError;
613 } else {
614 status = mirror::Class::kStatusNotReady;
615 }
616
Vladimir Marko49b0f452015-12-10 13:49:19 +0000617 writer_->oat_classes_.emplace_back(offset_,
618 compiled_methods_,
619 num_non_null_compiled_methods_,
620 status);
621 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100622 return DexMethodVisitor::EndClass();
623 }
624
625 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000626 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100627 size_t num_non_null_compiled_methods_;
628};
629
630class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
631 public:
632 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100633 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100634 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100635 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100636 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
637 }
638
639 bool EndClass() {
640 OatDexMethodVisitor::EndClass();
641 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100642 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100643 }
644 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100645 }
646
647 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700648 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000649 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100650 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
651
652 if (compiled_method != nullptr) {
653 // Derived from CompiledMethod.
654 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100655
Vladimir Marko35831e82015-09-11 11:59:18 +0100656 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
657 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800658 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800659
David Srbecky009e2a62015-04-15 02:46:30 +0100660 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100661 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800662 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000663 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000664 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
665 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800666 // Duplicate methods, we want the same code for both of them so that the oat writer puts
667 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800668 } else {
669 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100670 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800671 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000672 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100673 quick_code_offset = dedupe_map_.GetOrCreate(
674 compiled_method,
675 [this, &deduped, compiled_method, &it, thumb_offset]() {
676 deduped = false;
677 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
678 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800679 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100680
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100681 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000682 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100683 // TODO: Should this be a hard failure?
684 LOG(WARNING) << "Multiple definitions of "
685 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000686 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
687 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100688 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000689 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100690 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800691 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100692
Elliott Hughes956af0f2014-12-11 14:34:28 -0800693 // Update quick method header.
694 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
695 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800696 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100697 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
698 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100699 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800700 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
701 // to 0-offset and we need to adjust it by code_offset.
702 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100703 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800704 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100705 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800706 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800707 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
708 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
709 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100710 *method_header = OatQuickMethodHeader(vmap_table_offset,
711 frame_size_in_bytes,
712 core_spill_mask,
713 fp_spill_mask,
714 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100715
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000716 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800717 // Update offsets. (Checksum is updated when writing.)
718 offset_ += sizeof(*method_header); // Method header is prepended before code.
719 offset_ += code_size;
720 // Record absolute patch locations.
721 if (!compiled_method->GetPatches().empty()) {
722 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
723 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000724 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100725 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100726 }
727 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100728 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800729 }
Alex Light78382fa2014-06-06 15:45:32 -0700730
David Srbecky91cc06c2016-03-07 16:13:58 +0000731 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000732 // Exclude quickened dex methods (code_size == 0) since they have no native code.
733 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
734 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800735 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000736 debug::MethodDebugInfo info = debug::MethodDebugInfo();
737 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000738 info.dex_file = dex_file_;
739 info.class_def_index = class_def_index_;
740 info.dex_method_index = it.GetMemberIndex();
741 info.access_flags = it.GetMethodAccessFlags();
742 info.code_item = it.GetMethodCodeItem();
743 info.isa = compiled_method->GetInstructionSet();
744 info.deduped = deduped;
745 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
746 info.is_optimized = method_header->IsOptimized();
747 info.is_code_address_text_relative = true;
748 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
749 info.code_size = code_size;
750 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
751 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
752 info.cfi = compiled_method->GetCFIInfo();
753 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100754 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100756 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
757 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
758 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100759 ++method_offsets_index_;
760 }
761
762 return true;
763 }
764
765 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000766 struct CodeOffsetsKeyComparator {
767 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100768 // Code is deduplicated by CompilerDriver, compare only data pointers.
769 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
770 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000771 }
772 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100773 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
774 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000775 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100776 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
777 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000778 }
779 return false;
780 }
781 };
782
David Srbecky009e2a62015-04-15 02:46:30 +0100783 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
784 const ClassDataItemIterator& it,
785 uint32_t thumb_offset) {
786 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100787 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100788 offset_ = compiled_method->AlignCode(offset_);
789 DCHECK_ALIGNED_PARAM(offset_,
790 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
791 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
792 }
793
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794 // Deduplication is already done on a pointer basis by the compiler driver,
795 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100796 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100797
David Srbecky009e2a62015-04-15 02:46:30 +0100798 // Cache of compiler's --debuggable option.
799 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100800};
801
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100802class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
803 public:
804 InitMapMethodVisitor(OatWriter* writer, size_t offset)
805 : OatDexMethodVisitor(writer, offset) {
806 }
807
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700808 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700809 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000810 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100811 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
812
813 if (compiled_method != nullptr) {
814 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100815 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100816
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100817 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100818 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100819 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100820 size_t offset = dedupe_map_.GetOrCreate(
821 map.data(),
822 [this, map_size]() {
823 uint32_t new_offset = offset_;
824 offset_ += map_size;
825 return new_offset;
826 });
827 // Code offset is not initialized yet, so set the map offset to 0u-offset.
828 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
829 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100830 }
831 ++method_offsets_index_;
832 }
833
834 return true;
835 }
836
837 private:
838 // Deduplication is already done on a pointer basis by the compiler driver,
839 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100840 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841};
842
843class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
844 public:
845 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800846 : OatDexMethodVisitor(writer, offset),
847 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100848 }
849
850 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700851 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800852 const DexFile::TypeId& type_id =
853 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
854 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
855 // Skip methods that are not in the image.
856 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
857 return true;
858 }
859
Vladimir Marko49b0f452015-12-10 13:49:19 +0000860 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100861 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
862
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800863 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100864 if (compiled_method != nullptr) {
865 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
866 offsets = oat_class->method_offsets_[method_offsets_index_];
867 ++method_offsets_index_;
868 }
869
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100870 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100871 // Unchecked as we hold mutator_lock_ on entry.
872 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800873 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700874 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
875 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800876 ArtMethod* method;
877 if (writer_->HasBootImage()) {
878 const InvokeType invoke_type = it.GetMethodInvokeType(
879 dex_file_->GetClassDef(class_def_index_));
880 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
881 *dex_file_,
882 it.GetMemberIndex(),
883 dex_cache,
884 ScopedNullHandle<mirror::ClassLoader>(),
885 nullptr,
886 invoke_type);
887 if (method == nullptr) {
888 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
889 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
890 soa.Self()->AssertPendingException();
891 mirror::Throwable* exc = soa.Self()->GetException();
892 std::string dump = exc->Dump();
893 LOG(FATAL) << dump;
894 UNREACHABLE();
895 }
896 } else {
897 // Should already have been resolved by the compiler, just peek into the dex cache.
898 // It may not be resolved if the class failed to verify, in this case, don't set the
899 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
900 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700901 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800902 if (method != nullptr &&
903 compiled_method != nullptr &&
904 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100905 method->SetEntryPointFromQuickCompiledCodePtrSize(
906 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
907 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100908
909 return true;
910 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800911
912 protected:
913 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100914};
915
916class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
917 public:
918 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100919 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920 : OatDexMethodVisitor(writer, relative_offset),
921 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100922 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100923 soa_(Thread::Current()),
924 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100925 class_linker_(Runtime::Current()->GetClassLinker()),
926 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100927 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800928 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100929 // If we're creating the image, the address space must be ready so that we can apply patches.
930 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100931 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100932 }
933
Vladimir Markof4da6752014-08-01 19:04:18 +0100934 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100935 }
936
937 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700938 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100939 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
940 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700941 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000942 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100943 }
944 return true;
945 }
946
Mathieu Chartier90443472015-07-16 20:32:27 -0700947 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100948 bool result = OatDexMethodVisitor::EndClass();
949 if (oat_class_index_ == writer_->oat_classes_.size()) {
950 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000951 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100952 if (UNLIKELY(offset_ == 0u)) {
953 PLOG(ERROR) << "Failed to write final relative call thunks";
954 result = false;
955 }
956 }
957 return result;
958 }
959
960 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700961 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000962 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
964
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700965 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
966 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700967 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100968 size_t file_offset = file_offset_;
969 OutputStream* out = out_;
970
Vladimir Marko35831e82015-09-11 11:59:18 +0100971 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
972 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000973
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100974 // Deduplicate code arrays.
975 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
976 if (method_offsets.code_offset_ > offset_) {
977 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
978 if (offset_ == 0u) {
979 ReportWriteFailure("relative call thunk", it);
980 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000981 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100982 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
983 uint32_t aligned_code_delta = aligned_offset - offset_;
984 if (aligned_code_delta != 0) {
985 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
986 ReportWriteFailure("code alignment padding", it);
987 return false;
988 }
989 offset_ += aligned_code_delta;
990 DCHECK_OFFSET_();
991 }
992 DCHECK_ALIGNED_PARAM(offset_,
993 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
994 DCHECK_EQ(method_offsets.code_offset_,
995 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
996 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
997 const OatQuickMethodHeader& method_header =
998 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +0000999 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001000 ReportWriteFailure("method header", it);
1001 return false;
1002 }
1003 writer_->size_method_header_ += sizeof(method_header);
1004 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001005 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001006
1007 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001008 patched_code_.assign(quick_code.begin(), quick_code.end());
1009 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001010 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001011 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001012 switch (patch.GetType()) {
1013 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001014 // NOTE: Relative calls across oat files are not supported.
1015 uint32_t target_offset = GetTargetOffset(patch);
1016 writer_->relative_patcher_->PatchCall(&patched_code_,
1017 literal_offset,
1018 offset_ + literal_offset,
1019 target_offset);
1020 break;
1021 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001022 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001023 uint32_t target_offset = GetDexCacheOffset(patch);
1024 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1025 patch,
1026 offset_ + literal_offset,
1027 target_offset);
1028 break;
1029 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001030 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001031 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1032 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1033 patch,
1034 offset_ + literal_offset,
1035 target_offset);
1036 break;
1037 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001038 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001039 uint32_t target_offset = GetTargetOffset(patch);
1040 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1041 break;
1042 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001043 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001044 ArtMethod* method = GetTargetMethod(patch);
1045 PatchMethodAddress(&patched_code_, literal_offset, method);
1046 break;
1047 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001048 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001049 mirror::String* string = GetTargetString(patch);
1050 PatchObjectAddress(&patched_code_, literal_offset, string);
1051 break;
1052 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001053 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001054 mirror::Class* type = GetTargetType(patch);
1055 PatchObjectAddress(&patched_code_, literal_offset, type);
1056 break;
1057 }
1058 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001059 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001060 break;
1061 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001062 }
1063 }
1064 }
1065
Vladimir Marko49b0f452015-12-10 13:49:19 +00001066 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001067 ReportWriteFailure("method code", it);
1068 return false;
1069 }
1070 writer_->size_code_ += code_size;
1071 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001072 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001073 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001074 ++method_offsets_index_;
1075 }
1076
1077 return true;
1078 }
1079
1080 private:
1081 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001082 const size_t file_offset_;
1083 const ScopedObjectAccess soa_;
1084 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001085 ClassLinker* const class_linker_;
1086 mirror::DexCache* dex_cache_;
1087 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001088
1089 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1090 PLOG(ERROR) << "Failed to write " << what << " for "
1091 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1092 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001093
Mathieu Chartiere401d142015-04-22 13:56:20 -07001094 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001095 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001096 MethodReference ref = patch.TargetMethod();
1097 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001098 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1099 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001100 ArtMethod* method = dex_cache->GetResolvedMethod(
1101 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001102 CHECK(method != nullptr);
1103 return method;
1104 }
1105
Mathieu Chartier90443472015-07-16 20:32:27 -07001106 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001107 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1108 // If there's no new compiled code, either we're compiling an app and the target method
1109 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001110 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001111 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001112 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001113 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1114 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1115 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001116 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001117 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1118 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1119 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1120 target_offset = PointerToLowMemUInt32(oat_code_offset);
1121 } else {
1122 target_offset = target->IsNative()
1123 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1124 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1125 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001126 }
1127 return target_offset;
1128 }
1129
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001130 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001131 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001132 ? dex_cache_
1133 : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001134 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1135 CHECK(type != nullptr);
1136 return type;
1137 }
1138
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001139 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1140 mirror::String* string = dex_cache_->GetResolvedString(patch.TargetStringIndex());
1141 DCHECK(string != nullptr);
1142 DCHECK(writer_->HasBootImage() ||
1143 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1144 return string;
1145 }
1146
Mathieu Chartier90443472015-07-16 20:32:27 -07001147 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001148 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001149 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1150 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1151 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1152 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001153 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001154 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001155 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1156 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001157 }
1158 }
1159
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001160 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1161 DCHECK(writer_->HasBootImage());
1162 object = writer_->image_writer_->GetImageAddress(object);
1163 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1164 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1165 // TODO: Clean up offset types. The target offset must be treated as signed.
1166 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1167 }
1168
Vladimir Markof4da6752014-08-01 19:04:18 +01001169 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001170 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001171 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001172 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001173 } else {
1174 // NOTE: We're using linker patches for app->boot references when the image can
1175 // be relocated and therefore we need to emit .oat_patches. We're not using this
1176 // for app->app references, so check that the object is in the image space.
1177 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001178 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001179 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001180 uint32_t address = PointerToLowMemUInt32(object);
1181 DCHECK_LE(offset + 4, code->size());
1182 uint8_t* data = &(*code)[offset];
1183 data[0] = address & 0xffu;
1184 data[1] = (address >> 8) & 0xffu;
1185 data[2] = (address >> 16) & 0xffu;
1186 data[3] = (address >> 24) & 0xffu;
1187 }
1188
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001190 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001191 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001192 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001193 } else if (kIsDebugBuild) {
1194 // NOTE: We're using linker patches for app->boot references when the image can
1195 // be relocated and therefore we need to emit .oat_patches. We're not using this
1196 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001197 std::vector<gc::space::ImageSpace*> image_spaces =
1198 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1199 bool contains_method = false;
1200 for (gc::space::ImageSpace* image_space : image_spaces) {
1201 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1202 contains_method |=
1203 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1204 }
1205 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001206 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001207 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 uint32_t address = PointerToLowMemUInt32(method);
1209 DCHECK_LE(offset + 4, code->size());
1210 uint8_t* data = &(*code)[offset];
1211 data[0] = address & 0xffu;
1212 data[1] = (address >> 8) & 0xffu;
1213 data[2] = (address >> 16) & 0xffu;
1214 data[3] = (address >> 24) & 0xffu;
1215 }
1216
Vladimir Markof4da6752014-08-01 19:04:18 +01001217 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001218 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001219 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001220 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001221 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1222 // TODO: Clean up offset types.
1223 // The target_offset must be treated as signed for cross-oat patching.
1224 const void* target = reinterpret_cast<const void*>(
1225 writer_->image_writer_->GetOatDataBegin(oat_index) +
1226 static_cast<int32_t>(target_offset));
1227 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001228 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001229 DCHECK_LE(offset + 4, code->size());
1230 uint8_t* data = &(*code)[offset];
1231 data[0] = address & 0xffu;
1232 data[1] = (address >> 8) & 0xffu;
1233 data[2] = (address >> 16) & 0xffu;
1234 data[3] = (address >> 24) & 0xffu;
1235 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001236};
1237
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001238class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1239 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001240 WriteMapMethodVisitor(OatWriter* writer,
1241 OutputStream* out,
1242 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001243 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001244 : OatDexMethodVisitor(writer, relative_offset),
1245 out_(out),
1246 file_offset_(file_offset) {
1247 }
1248
1249 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001250 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001251 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1252
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001253 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001254 size_t file_offset = file_offset_;
1255 OutputStream* out = out_;
1256
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001257 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1258 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001259 ++method_offsets_index_;
1260
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001261 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1262 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1263 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1264 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1265
1266 if (map_offset != 0u) {
1267 // Transform map_offset to actual oat data offset.
1268 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1269 DCHECK_NE(map_offset, 0u);
1270 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1271
1272 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1273 size_t map_size = map.size() * sizeof(map[0]);
1274 if (map_offset == offset_) {
1275 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
1276 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
1277 ReportWriteFailure(it);
1278 return false;
1279 }
1280 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001281 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001282 }
1283 DCHECK_OFFSET_();
1284 }
1285
1286 return true;
1287 }
1288
1289 private:
1290 OutputStream* const out_;
1291 size_t const file_offset_;
1292
1293 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001294 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001295 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1296 }
1297};
1298
1299// Visit all methods from all classes in all dex files with the specified visitor.
1300bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1301 for (const DexFile* dex_file : *dex_files_) {
1302 const size_t class_def_count = dex_file->NumClassDefs();
1303 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1304 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1305 return false;
1306 }
1307 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001308 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001309 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001310 ClassDataItemIterator it(*dex_file, class_data);
1311 while (it.HasNextStaticField()) {
1312 it.Next();
1313 }
1314 while (it.HasNextInstanceField()) {
1315 it.Next();
1316 }
1317 size_t class_def_method_index = 0u;
1318 while (it.HasNextDirectMethod()) {
1319 if (!visitor->VisitMethod(class_def_method_index, it)) {
1320 return false;
1321 }
1322 ++class_def_method_index;
1323 it.Next();
1324 }
1325 while (it.HasNextVirtualMethod()) {
1326 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1327 return false;
1328 }
1329 ++class_def_method_index;
1330 it.Next();
1331 }
1332 }
1333 if (UNLIKELY(!visitor->EndClass())) {
1334 return false;
1335 }
1336 }
1337 }
1338 return true;
1339}
1340
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001341size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1342 const InstructionSetFeatures* instruction_set_features,
1343 uint32_t num_dex_files,
1344 SafeMap<std::string, std::string>* key_value_store) {
1345 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1346 oat_header_.reset(OatHeader::Create(instruction_set,
1347 instruction_set_features,
1348 num_dex_files,
1349 key_value_store));
1350 size_oat_header_ += sizeof(OatHeader);
1351 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001352 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001353}
1354
1355size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001356 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1357 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001358 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001359 oat_dex_file.offset_ = offset;
1360 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001361 }
1362 return offset;
1363}
1364
Brian Carlstrom389efb02012-01-11 12:06:26 -08001365size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001366 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001367 InitOatClassesMethodVisitor visitor(this, offset);
1368 bool success = VisitDexMethods(&visitor);
1369 CHECK(success);
1370 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001371
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001372 // Update oat_dex_files_.
1373 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001374 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1375 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001376 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001377 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001378 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001379 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001380 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001381 CHECK(oat_class_it == oat_classes_.end());
1382
1383 return offset;
1384}
1385
1386size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001387 InitMapMethodVisitor visitor(this, offset);
1388 bool success = VisitDexMethods(&visitor);
1389 DCHECK(success);
1390 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001391
Brian Carlstrome24fa612011-09-29 00:53:55 -07001392 return offset;
1393}
1394
1395size_t OatWriter::InitOatCode(size_t offset) {
1396 // calculate the offsets within OatHeader to executable code
1397 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001398 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001399 // required to be on a new page boundary
1400 offset = RoundUp(offset, kPageSize);
1401 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001402 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001403 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001404 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001405
Ian Rogers848871b2013-08-05 10:56:33 -07001406 #define DO_TRAMPOLINE(field, fn_name) \
1407 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001408 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1409 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Vladimir Markod1ee8092016-04-13 11:59:46 +01001410 field = compiler_driver_->Create ## fn_name(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001411 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001412
Ian Rogers848871b2013-08-05 10:56:33 -07001413 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001414 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001415 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001416 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1417 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001418
Ian Rogers848871b2013-08-05 10:56:33 -07001419 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001420 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001421 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1422 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1423 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001424 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001425 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001426 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001427 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001428 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001429 return offset;
1430}
1431
1432size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001433 #define VISIT(VisitorType) \
1434 do { \
1435 VisitorType visitor(this, offset); \
1436 bool success = VisitDexMethods(&visitor); \
1437 DCHECK(success); \
1438 offset = visitor.GetOffset(); \
1439 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001440
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001441 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001442 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001443 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001444 }
Logan Chien8b977d32012-02-21 19:14:55 +08001445
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001446 #undef VISIT
1447
Brian Carlstrome24fa612011-09-29 00:53:55 -07001448 return offset;
1449}
1450
David Srbeckybc90fd02015-04-22 19:40:27 +01001451bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001452 CHECK(write_state_ == WriteState::kWriteRoData);
1453
1454 if (!WriteClassOffsets(out)) {
1455 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001456 return false;
1457 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001458
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001459 if (!WriteClasses(out)) {
1460 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001461 return false;
1462 }
1463
Vladimir Markof4da6752014-08-01 19:04:18 +01001464 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001465 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001466 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1467 return false;
1468 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001469 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001470 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001471 relative_offset = WriteMaps(out, file_offset, relative_offset);
1472 if (relative_offset == 0) {
1473 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1474 return false;
1475 }
1476
David Srbeckybc90fd02015-04-22 19:40:27 +01001477 // Write padding.
1478 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1479 relative_offset += size_executable_offset_alignment_;
1480 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1481 size_t expected_file_offset = file_offset + relative_offset;
1482 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1483 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1484 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1485 return 0;
1486 }
1487 DCHECK_OFFSET();
1488
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001489 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001490 return true;
1491}
1492
1493bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001494 CHECK(write_state_ == WriteState::kWriteText);
1495
Vladimir Marko944da602016-02-19 12:27:55 +00001496 SetMultiOatRelativePatcherAdjustment();
1497
David Srbeckybc90fd02015-04-22 19:40:27 +01001498 const size_t file_offset = oat_data_offset_;
1499 size_t relative_offset = oat_header_->GetExecutableOffset();
1500 DCHECK_OFFSET();
1501
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001502 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001503 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001504 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001505 return false;
1506 }
1507
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001508 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1509 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001510 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001511 return false;
1512 }
1513
Vladimir Markof4da6752014-08-01 19:04:18 +01001514 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001515 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001516 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1517 return false;
1518 }
1519
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001520 if (kIsDebugBuild) {
1521 uint32_t size_total = 0;
1522 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001523 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001524 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001525
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001526 DO_STAT(size_dex_file_alignment_);
1527 DO_STAT(size_executable_offset_alignment_);
1528 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001529 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001530 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001531 DO_STAT(size_interpreter_to_interpreter_bridge_);
1532 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1533 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001534 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001535 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001536 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001537 DO_STAT(size_quick_to_interpreter_bridge_);
1538 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001539 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001540 DO_STAT(size_code_);
1541 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001542 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001543 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001544 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001545 DO_STAT(size_oat_dex_file_location_size_);
1546 DO_STAT(size_oat_dex_file_location_data_);
1547 DO_STAT(size_oat_dex_file_location_checksum_);
1548 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001549 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001550 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001551 DO_STAT(size_oat_lookup_table_alignment_);
1552 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001553 DO_STAT(size_oat_class_offsets_alignment_);
1554 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001555 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001556 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001557 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001558 DO_STAT(size_oat_class_method_offsets_);
1559 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001560
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001561 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001562 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001563 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001564 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001565
Vladimir Markof4da6752014-08-01 19:04:18 +01001566 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001567 CHECK_EQ(size_, relative_offset);
1568
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001569 write_state_ = WriteState::kWriteHeader;
1570 return true;
1571}
1572
1573bool OatWriter::WriteHeader(OutputStream* out,
1574 uint32_t image_file_location_oat_checksum,
1575 uintptr_t image_file_location_oat_begin,
1576 int32_t image_patch_delta) {
1577 CHECK(write_state_ == WriteState::kWriteHeader);
1578
1579 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1580 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1581 if (compiler_driver_->IsBootImage()) {
1582 CHECK_EQ(image_patch_delta, 0);
1583 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1584 } else {
1585 CHECK_ALIGNED(image_patch_delta, kPageSize);
1586 oat_header_->SetImagePatchDelta(image_patch_delta);
1587 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001588 oat_header_->UpdateChecksumWithHeaderData();
1589
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001590 const size_t file_offset = oat_data_offset_;
1591
1592 off_t current_offset = out->Seek(0, kSeekCurrent);
1593 if (current_offset == static_cast<off_t>(-1)) {
1594 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1595 return false;
1596 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001597 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001598 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1599 return false;
1600 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001601 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001602
1603 // Flush all other data before writing the header.
1604 if (!out->Flush()) {
1605 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1606 return false;
1607 }
1608 // Write the header.
1609 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001610 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001611 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1612 return false;
1613 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001614 // Flush the header data.
1615 if (!out->Flush()) {
1616 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001617 return false;
1618 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001619
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001620 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1621 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1622 return false;
1623 }
1624 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1625
1626 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001627 return true;
1628}
1629
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001630bool OatWriter::WriteClassOffsets(OutputStream* out) {
1631 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1632 if (oat_dex_file.class_offsets_offset_ != 0u) {
1633 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1634 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1635 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1636 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1637 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001638 return false;
1639 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001640 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1641 return false;
1642 }
1643 }
1644 }
1645 return true;
1646}
1647
1648bool OatWriter::WriteClasses(OutputStream* out) {
1649 for (OatClass& oat_class : oat_classes_) {
1650 if (!oat_class.Write(this, out, oat_data_offset_)) {
1651 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1652 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001653 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001654 }
1655 return true;
1656}
1657
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001658size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001659 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001660 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1661 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1662 return 0;
1663 }
1664 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001665 size_vmap_table_ = relative_offset - vmap_tables_offset;
1666
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001667 return relative_offset;
1668}
1669
1670size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001671 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001672 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001673
Ian Rogers848871b2013-08-05 10:56:33 -07001674 #define DO_TRAMPOLINE(field) \
1675 do { \
1676 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1677 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001678 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001679 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001680 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001681 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001682 return false; \
1683 } \
1684 size_ ## field += field->size(); \
1685 relative_offset += alignment_padding + field->size(); \
1686 DCHECK_OFFSET(); \
1687 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001688
Ian Rogers848871b2013-08-05 10:56:33 -07001689 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001690 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001691 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001692 DO_TRAMPOLINE(quick_resolution_trampoline_);
1693 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1694 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001695 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001696 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001697}
1698
Ian Rogers3d504072014-03-01 09:16:49 -08001699size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001700 const size_t file_offset,
1701 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001702 #define VISIT(VisitorType) \
1703 do { \
1704 VisitorType visitor(this, out, file_offset, relative_offset); \
1705 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1706 return 0; \
1707 } \
1708 relative_offset = visitor.GetOffset(); \
1709 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001710
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001711 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001712
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001713 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001714
Vladimir Markob163bb72015-03-31 21:49:49 +01001715 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1716 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1717 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1718
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001719 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001720}
1721
Vladimir Marko944da602016-02-19 12:27:55 +00001722bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001723 // Get the elf file offset of the oat file.
1724 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1725 if (raw_file_offset == static_cast<off_t>(-1)) {
1726 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1727 return false;
1728 }
1729 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1730 return true;
1731}
1732
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001733bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1734 // Read the dex file header and perform minimal verification.
1735 uint8_t raw_header[sizeof(DexFile::Header)];
1736 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1737 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1738 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1739 return false;
1740 }
1741 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1742 return false;
1743 }
1744
1745 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1746 oat_dex_file->dex_file_size_ = header->file_size_;
1747 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1748 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1749 return true;
1750}
1751
1752bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1753 if (!DexFile::IsMagicValid(raw_header)) {
1754 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1755 return false;
1756 }
1757 if (!DexFile::IsVersionValid(raw_header)) {
1758 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1759 return false;
1760 }
1761 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1762 if (header->file_size_ < sizeof(DexFile::Header)) {
1763 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1764 << " File: " << location;
1765 return false;
1766 }
1767 return true;
1768}
1769
1770bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1771 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1772
1773 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001774 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001775 return false;
1776 }
1777
1778 // Write dex files.
1779 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1780 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1781 return false;
1782 }
1783 }
1784
1785 // Close sources.
1786 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1787 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1788 }
1789 zipped_dex_files_.clear();
1790 zip_archives_.clear();
1791 raw_dex_files_.clear();
1792 return true;
1793}
1794
1795bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1796 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1797 return false;
1798 }
1799 if (oat_dex_file->source_.IsZipEntry()) {
1800 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1801 return false;
1802 }
1803 } else if (oat_dex_file->source_.IsRawFile()) {
1804 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1805 return false;
1806 }
1807 } else {
1808 DCHECK(oat_dex_file->source_.IsRawData());
1809 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1810 return false;
1811 }
1812 }
1813
1814 // Update current size and account for the written data.
1815 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1816 size_ += oat_dex_file->dex_file_size_;
1817 size_dex_file_ += oat_dex_file->dex_file_size_;
1818 return true;
1819}
1820
1821bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1822 // Dex files are required to be 4 byte aligned.
1823 size_t original_offset = size_;
1824 size_t offset = RoundUp(original_offset, 4);
1825 size_dex_file_alignment_ += offset - original_offset;
1826
1827 // Seek to the start of the dex file and flush any pending operations in the stream.
1828 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1829 uint32_t start_offset = oat_data_offset_ + offset;
1830 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1831 if (actual_offset != static_cast<off_t>(start_offset)) {
1832 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1833 << " Expected: " << start_offset
1834 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1835 return false;
1836 }
1837 if (!out->Flush()) {
1838 PLOG(ERROR) << "Failed to flush before writing dex file."
1839 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1840 return false;
1841 }
1842 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1843 if (actual_offset != static_cast<off_t>(start_offset)) {
1844 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1845 << " Expected: " << start_offset
1846 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1847 return false;
1848 }
1849
1850 size_ = offset;
1851 oat_dex_file->dex_file_offset_ = offset;
1852 return true;
1853}
1854
1855bool OatWriter::WriteDexFile(OutputStream* rodata,
1856 File* file,
1857 OatDexFile* oat_dex_file,
1858 ZipEntry* dex_file) {
1859 size_t start_offset = oat_data_offset_ + size_;
1860 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1861
1862 // Extract the dex file and get the extracted size.
1863 std::string error_msg;
1864 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1865 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1866 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1867 return false;
1868 }
1869 if (file->Flush() != 0) {
1870 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1871 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1872 return false;
1873 }
1874 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1875 if (extracted_end == static_cast<off_t>(-1)) {
1876 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1877 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1878 return false;
1879 }
1880 if (extracted_end < static_cast<off_t>(start_offset)) {
1881 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1882 << " Start: " << start_offset
1883 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1884 return false;
1885 }
1886 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1887 if (extracted_size < sizeof(DexFile::Header)) {
1888 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1889 << extracted_size << " File: " << oat_dex_file->GetLocation();
1890 return false;
1891 }
1892
1893 // Read the dex file header and extract required data to OatDexFile.
1894 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1895 if (actual_offset != static_cast<off_t>(start_offset)) {
1896 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1897 << " Expected: " << start_offset
1898 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1899 return false;
1900 }
1901 if (!ReadDexFileHeader(file, oat_dex_file)) {
1902 return false;
1903 }
1904 if (extracted_size < oat_dex_file->dex_file_size_) {
1905 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1906 << " file size from header: " << oat_dex_file->dex_file_size_
1907 << " File: " << oat_dex_file->GetLocation();
1908 return false;
1909 }
1910
1911 // Override the checksum from header with the CRC from ZIP entry.
1912 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1913
1914 // Seek both file and stream to the end offset.
1915 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1916 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1917 if (actual_offset != static_cast<off_t>(end_offset)) {
1918 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1919 << " Expected: " << end_offset
1920 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1921 return false;
1922 }
1923 actual_offset = rodata->Seek(end_offset, kSeekSet);
1924 if (actual_offset != static_cast<off_t>(end_offset)) {
1925 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1926 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1927 return false;
1928 }
1929 if (!rodata->Flush()) {
1930 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1931 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1932 return false;
1933 }
1934
1935 // If we extracted more than the size specified in the header, truncate the file.
1936 if (extracted_size > oat_dex_file->dex_file_size_) {
1937 if (file->SetLength(end_offset) != 0) {
1938 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1939 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1940 return false;
1941 }
1942 }
1943
1944 return true;
1945}
1946
1947bool OatWriter::WriteDexFile(OutputStream* rodata,
1948 File* file,
1949 OatDexFile* oat_dex_file,
1950 File* dex_file) {
1951 size_t start_offset = oat_data_offset_ + size_;
1952 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1953
1954 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
1955 if (input_offset != static_cast<off_t>(0)) {
1956 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
1957 << " Expected: 0"
1958 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1959 return false;
1960 }
1961 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
1962 return false;
1963 }
1964
1965 // Copy the input dex file using sendfile().
1966 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
1967 PLOG(ERROR) << "Failed to copy dex file to oat file."
1968 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1969 return false;
1970 }
1971 if (file->Flush() != 0) {
1972 PLOG(ERROR) << "Failed to flush dex file."
1973 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1974 return false;
1975 }
1976
1977 // Check file position and seek the stream to the end offset.
1978 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1979 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1980 if (actual_offset != static_cast<off_t>(end_offset)) {
1981 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
1982 << " Expected: " << end_offset
1983 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1984 return false;
1985 }
1986 actual_offset = rodata->Seek(end_offset, kSeekSet);
1987 if (actual_offset != static_cast<off_t>(end_offset)) {
1988 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1989 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1990 return false;
1991 }
1992 if (!rodata->Flush()) {
1993 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1994 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1995 return false;
1996 }
1997
1998 return true;
1999}
2000
2001bool OatWriter::WriteDexFile(OutputStream* rodata,
2002 OatDexFile* oat_dex_file,
2003 const uint8_t* dex_file) {
2004 // Note: The raw data has already been checked to contain the header
2005 // and all the data that the header specifies as the file size.
2006 DCHECK(dex_file != nullptr);
2007 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2008 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2009
2010 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2011 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2012 << " to " << rodata->GetLocation();
2013 return false;
2014 }
2015 if (!rodata->Flush()) {
2016 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2017 << " File: " << oat_dex_file->GetLocation();
2018 return false;
2019 }
2020
2021 // Update dex file size and resize class offsets in the OatDexFile.
2022 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2023 oat_dex_file->dex_file_size_ = header->file_size_;
2024 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2025 return true;
2026}
2027
2028bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2029 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2030
2031 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2032 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2033 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2034 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2035 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2036 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2037 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2038 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2039 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2040 return false;
2041 }
2042
2043 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2044 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2045
2046 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2047 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2048
2049 // Write OatDexFile.
2050 if (!oat_dex_file->Write(this, rodata)) {
2051 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2052 return false;
2053 }
2054 }
2055
2056 return true;
2057}
2058
2059bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2060 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2061
2062 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2063 if (file->SetLength(new_length) != 0) {
2064 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2065 << "File: " << file->GetPath();
2066 return false;
2067 }
2068 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2069 if (actual_offset != static_cast<off_t>(new_length)) {
2070 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2071 << " Actual: " << actual_offset << " Expected: " << new_length
2072 << " File: " << rodata->GetLocation();
2073 return false;
2074 }
2075 if (!rodata->Flush()) {
2076 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2077 << " File: " << rodata->GetLocation();
2078 return false;
2079 }
2080 return true;
2081}
2082
2083bool OatWriter::OpenDexFiles(
2084 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002085 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002086 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2087 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2088 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2089
2090 if (oat_dex_files_.empty()) {
2091 // Nothing to do.
2092 return true;
2093 }
2094
2095 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2096 size_t length = size_ - map_offset;
2097 std::string error_msg;
2098 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2099 PROT_READ | PROT_WRITE,
2100 MAP_SHARED,
2101 file->Fd(),
2102 oat_data_offset_ + map_offset,
2103 /* low_4gb */ false,
2104 file->GetPath().c_str(),
2105 &error_msg));
2106 if (dex_files_map == nullptr) {
2107 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2108 << " error: " << error_msg;
2109 return false;
2110 }
2111 std::vector<std::unique_ptr<const DexFile>> dex_files;
2112 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2113 // Make sure no one messed with input files while we were copying data.
2114 // At the very least we need consistent file size and number of class definitions.
2115 const uint8_t* raw_dex_file =
2116 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2117 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2118 // Note: ValidateDexFileHeader() already logged an error message.
2119 LOG(ERROR) << "Failed to verify written dex file header!"
2120 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2121 << " ~ " << static_cast<const void*>(raw_dex_file);
2122 return false;
2123 }
2124 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2125 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2126 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2127 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2128 << " Output: " << file->GetPath();
2129 return false;
2130 }
2131 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2132 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2133 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2134 << " Output: " << file->GetPath();
2135 return false;
2136 }
2137
2138 // Now, open the dex file.
2139 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2140 oat_dex_file.dex_file_size_,
2141 oat_dex_file.GetLocation(),
2142 oat_dex_file.dex_file_location_checksum_,
2143 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002144 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002145 &error_msg));
2146 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002147 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2148 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002149 return false;
2150 }
2151 }
2152
2153 *opened_dex_files_map = std::move(dex_files_map);
2154 *opened_dex_files = std::move(dex_files);
2155 return true;
2156}
2157
2158bool OatWriter::WriteTypeLookupTables(
2159 MemMap* opened_dex_files_map,
2160 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2161 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2162
2163 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2164 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2165 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2166 if (oat_dex_file->lookup_table_offset_ != 0u) {
2167 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2168 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2169 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2170 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2171 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2172 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2173 }
2174 }
2175
2176 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2177 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2178 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2179 return false;
2180 }
2181
2182 return true;
2183}
2184
Vladimir Markof4da6752014-08-01 19:04:18 +01002185bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2186 static const uint8_t kPadding[] = {
2187 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2188 };
2189 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2190 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2191 return false;
2192 }
2193 size_code_alignment_ += aligned_code_delta;
2194 return true;
2195}
2196
Vladimir Marko49b0f452015-12-10 13:49:19 +00002197bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2198 oat_header_->UpdateChecksum(data, size);
2199 return out->WriteFully(data, size);
2200}
2201
Vladimir Marko944da602016-02-19 12:27:55 +00002202void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2203 DCHECK(dex_files_ != nullptr);
2204 DCHECK(relative_patcher_ != nullptr);
2205 DCHECK_NE(oat_data_offset_, 0u);
2206 if (image_writer_ != nullptr && !dex_files_->empty()) {
2207 // The oat data begin may not be initialized yet but the oat file offset is ready.
2208 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2209 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2210 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002211 }
2212}
2213
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002214OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2215 DexFileSource source,
2216 CreateTypeLookupTable create_type_lookup_table)
2217 : source_(source),
2218 create_type_lookup_table_(create_type_lookup_table),
2219 dex_file_size_(0),
2220 offset_(0),
2221 dex_file_location_size_(strlen(dex_file_location)),
2222 dex_file_location_data_(dex_file_location),
2223 dex_file_location_checksum_(0u),
2224 dex_file_offset_(0u),
2225 class_offsets_offset_(0u),
2226 lookup_table_offset_(0u),
2227 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002228}
2229
2230size_t OatWriter::OatDexFile::SizeOf() const {
2231 return sizeof(dex_file_location_size_)
2232 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002233 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002234 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002235 + sizeof(class_offsets_offset_)
2236 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002237}
2238
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002239void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2240 DCHECK_EQ(lookup_table_offset_, 0u);
2241 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2242 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2243 if (table_size != 0u) {
2244 // Type tables are required to be 4 byte aligned.
2245 size_t original_offset = oat_writer->size_;
2246 size_t offset = RoundUp(original_offset, 4);
2247 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2248 lookup_table_offset_ = offset;
2249 oat_writer->size_ = offset + table_size;
2250 oat_writer->size_oat_lookup_table_ += table_size;
2251 }
2252 }
2253}
2254
2255void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2256 DCHECK_EQ(class_offsets_offset_, 0u);
2257 if (!class_offsets_.empty()) {
2258 // Class offsets are required to be 4 byte aligned.
2259 size_t original_offset = oat_writer->size_;
2260 size_t offset = RoundUp(original_offset, 4);
2261 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2262 class_offsets_offset_ = offset;
2263 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2264 }
2265}
2266
2267bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2268 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002269 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002270
Vladimir Marko49b0f452015-12-10 13:49:19 +00002271 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002272 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002273 return false;
2274 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002275 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002276
Vladimir Marko49b0f452015-12-10 13:49:19 +00002277 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002278 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002279 return false;
2280 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002281 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002282
Vladimir Marko49b0f452015-12-10 13:49:19 +00002283 if (!oat_writer->WriteData(out,
2284 &dex_file_location_checksum_,
2285 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002286 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002287 return false;
2288 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002289 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002290
Vladimir Marko49b0f452015-12-10 13:49:19 +00002291 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002292 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002293 return false;
2294 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002295 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002296
2297 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2298 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2299 return false;
2300 }
2301 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2302
Vladimir Marko49b0f452015-12-10 13:49:19 +00002303 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002304 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2305 return false;
2306 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002307 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002308
2309 return true;
2310}
2311
2312bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002313 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002314 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2315 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002316 return false;
2317 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002318 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002319 return true;
2320}
2321
Brian Carlstromba150c32013-08-27 17:31:03 -07002322OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002323 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002324 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002325 mirror::Class::Status status)
2326 : compiled_methods_(compiled_methods) {
2327 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002328 CHECK_LE(num_non_null_compiled_methods, num_methods);
2329
Brian Carlstrom265091e2013-01-30 14:08:26 -08002330 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002331 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2332
2333 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2334 // apply when there are 0 methods, we just arbitrarily say that 0
2335 // methods means kOatClassNoneCompiled and that we won't use
2336 // kOatClassAllCompiled unless there is at least one compiled
2337 // method. This means in an interpretter only system, we can assert
2338 // that all classes are kOatClassNoneCompiled.
2339 if (num_non_null_compiled_methods == 0) {
2340 type_ = kOatClassNoneCompiled;
2341 } else if (num_non_null_compiled_methods == num_methods) {
2342 type_ = kOatClassAllCompiled;
2343 } else {
2344 type_ = kOatClassSomeCompiled;
2345 }
2346
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002347 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002348 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002349 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002350
2351 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2352 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002353 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002354 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2355 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2356 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2357 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002358 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002359 method_bitmap_size_ = 0;
2360 }
2361
2362 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002363 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002364 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002365 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2366 } else {
2367 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2368 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2369 if (type_ == kOatClassSomeCompiled) {
2370 method_bitmap_->SetBit(i);
2371 }
2372 }
2373 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002374}
2375
Brian Carlstrom265091e2013-01-30 14:08:26 -08002376size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2377 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002378 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2379 if (method_offset == 0) {
2380 return 0;
2381 }
2382 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002383}
2384
2385size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2386 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002387 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002388}
2389
2390size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002391 return sizeof(status_)
2392 + sizeof(type_)
2393 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2394 + method_bitmap_size_
2395 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002396}
2397
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002398bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002399 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002400 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002401 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002402 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002403 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002404 return false;
2405 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002406 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002407
2408 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002409 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002410 return false;
2411 }
2412 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002413
Brian Carlstromba150c32013-08-27 17:31:03 -07002414 if (method_bitmap_size_ != 0) {
2415 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002416 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002417 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002418 return false;
2419 }
2420 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002421
2422 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002423 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002424 return false;
2425 }
2426 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2427 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002428
2429 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002430 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002431 return false;
2432 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002433 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002434 return true;
2435}
2436
Brian Carlstrome24fa612011-09-29 00:53:55 -07002437} // namespace art