blob: 1aa26090ad4cee16a377e84be05698cfc7b30fc8 [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 Marko052164a2016-04-27 13:54:18 +01001130 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
1131 SHARED_REQUIRES(Locks::mutator_lock_) {
1132 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001133 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001134 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1135 }
1136
1137 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1138 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001139 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1140 CHECK(type != nullptr);
1141 return type;
1142 }
1143
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001144 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001145 mirror::DexCache* dex_cache = GetDexCache(patch.TargetStringDexFile());
1146 mirror::String* string = dex_cache->GetResolvedString(patch.TargetStringIndex());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001147 DCHECK(string != nullptr);
1148 DCHECK(writer_->HasBootImage() ||
1149 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1150 return string;
1151 }
1152
Mathieu Chartier90443472015-07-16 20:32:27 -07001153 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001154 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001155 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1156 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1157 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1158 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001159 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001160 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001161 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1162 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001163 }
1164 }
1165
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001166 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1167 DCHECK(writer_->HasBootImage());
1168 object = writer_->image_writer_->GetImageAddress(object);
1169 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1170 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1171 // TODO: Clean up offset types. The target offset must be treated as signed.
1172 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1173 }
1174
Vladimir Markof4da6752014-08-01 19:04:18 +01001175 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001176 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001177 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001178 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001179 } else {
1180 // NOTE: We're using linker patches for app->boot references when the image can
1181 // be relocated and therefore we need to emit .oat_patches. We're not using this
1182 // for app->app references, so check that the object is in the image space.
1183 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001184 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001185 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001186 uint32_t address = PointerToLowMemUInt32(object);
1187 DCHECK_LE(offset + 4, code->size());
1188 uint8_t* data = &(*code)[offset];
1189 data[0] = address & 0xffu;
1190 data[1] = (address >> 8) & 0xffu;
1191 data[2] = (address >> 16) & 0xffu;
1192 data[3] = (address >> 24) & 0xffu;
1193 }
1194
Mathieu Chartiere401d142015-04-22 13:56:20 -07001195 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001196 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001197 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001198 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001199 } else if (kIsDebugBuild) {
1200 // NOTE: We're using linker patches for app->boot references when the image can
1201 // be relocated and therefore we need to emit .oat_patches. We're not using this
1202 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001203 std::vector<gc::space::ImageSpace*> image_spaces =
1204 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1205 bool contains_method = false;
1206 for (gc::space::ImageSpace* image_space : image_spaces) {
1207 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1208 contains_method |=
1209 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1210 }
1211 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001212 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001213 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001214 uint32_t address = PointerToLowMemUInt32(method);
1215 DCHECK_LE(offset + 4, code->size());
1216 uint8_t* data = &(*code)[offset];
1217 data[0] = address & 0xffu;
1218 data[1] = (address >> 8) & 0xffu;
1219 data[2] = (address >> 16) & 0xffu;
1220 data[3] = (address >> 24) & 0xffu;
1221 }
1222
Vladimir Markof4da6752014-08-01 19:04:18 +01001223 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001224 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001225 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001226 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001227 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1228 // TODO: Clean up offset types.
1229 // The target_offset must be treated as signed for cross-oat patching.
1230 const void* target = reinterpret_cast<const void*>(
1231 writer_->image_writer_->GetOatDataBegin(oat_index) +
1232 static_cast<int32_t>(target_offset));
1233 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001234 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001235 DCHECK_LE(offset + 4, code->size());
1236 uint8_t* data = &(*code)[offset];
1237 data[0] = address & 0xffu;
1238 data[1] = (address >> 8) & 0xffu;
1239 data[2] = (address >> 16) & 0xffu;
1240 data[3] = (address >> 24) & 0xffu;
1241 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001242};
1243
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001244class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1245 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001246 WriteMapMethodVisitor(OatWriter* writer,
1247 OutputStream* out,
1248 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001249 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001250 : OatDexMethodVisitor(writer, relative_offset),
1251 out_(out),
1252 file_offset_(file_offset) {
1253 }
1254
1255 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001256 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001257 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1258
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001259 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001260 size_t file_offset = file_offset_;
1261 OutputStream* out = out_;
1262
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001263 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1264 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001265 ++method_offsets_index_;
1266
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001267 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1268 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1269 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1270 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1271
1272 if (map_offset != 0u) {
1273 // Transform map_offset to actual oat data offset.
1274 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1275 DCHECK_NE(map_offset, 0u);
1276 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1277
1278 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1279 size_t map_size = map.size() * sizeof(map[0]);
1280 if (map_offset == offset_) {
1281 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
1282 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
1283 ReportWriteFailure(it);
1284 return false;
1285 }
1286 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001287 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001288 }
1289 DCHECK_OFFSET_();
1290 }
1291
1292 return true;
1293 }
1294
1295 private:
1296 OutputStream* const out_;
1297 size_t const file_offset_;
1298
1299 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001300 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001301 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1302 }
1303};
1304
1305// Visit all methods from all classes in all dex files with the specified visitor.
1306bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1307 for (const DexFile* dex_file : *dex_files_) {
1308 const size_t class_def_count = dex_file->NumClassDefs();
1309 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1310 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1311 return false;
1312 }
1313 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001314 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001315 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001316 ClassDataItemIterator it(*dex_file, class_data);
1317 while (it.HasNextStaticField()) {
1318 it.Next();
1319 }
1320 while (it.HasNextInstanceField()) {
1321 it.Next();
1322 }
1323 size_t class_def_method_index = 0u;
1324 while (it.HasNextDirectMethod()) {
1325 if (!visitor->VisitMethod(class_def_method_index, it)) {
1326 return false;
1327 }
1328 ++class_def_method_index;
1329 it.Next();
1330 }
1331 while (it.HasNextVirtualMethod()) {
1332 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1333 return false;
1334 }
1335 ++class_def_method_index;
1336 it.Next();
1337 }
1338 }
1339 if (UNLIKELY(!visitor->EndClass())) {
1340 return false;
1341 }
1342 }
1343 }
1344 return true;
1345}
1346
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001347size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1348 const InstructionSetFeatures* instruction_set_features,
1349 uint32_t num_dex_files,
1350 SafeMap<std::string, std::string>* key_value_store) {
1351 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1352 oat_header_.reset(OatHeader::Create(instruction_set,
1353 instruction_set_features,
1354 num_dex_files,
1355 key_value_store));
1356 size_oat_header_ += sizeof(OatHeader);
1357 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001358 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001359}
1360
1361size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001362 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1363 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001364 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001365 oat_dex_file.offset_ = offset;
1366 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001367 }
1368 return offset;
1369}
1370
Brian Carlstrom389efb02012-01-11 12:06:26 -08001371size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001372 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001373 InitOatClassesMethodVisitor visitor(this, offset);
1374 bool success = VisitDexMethods(&visitor);
1375 CHECK(success);
1376 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001377
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001378 // Update oat_dex_files_.
1379 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001380 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1381 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001382 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001383 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001384 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001385 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001386 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001387 CHECK(oat_class_it == oat_classes_.end());
1388
1389 return offset;
1390}
1391
1392size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001393 InitMapMethodVisitor visitor(this, offset);
1394 bool success = VisitDexMethods(&visitor);
1395 DCHECK(success);
1396 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001397
Brian Carlstrome24fa612011-09-29 00:53:55 -07001398 return offset;
1399}
1400
1401size_t OatWriter::InitOatCode(size_t offset) {
1402 // calculate the offsets within OatHeader to executable code
1403 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001404 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001405 // required to be on a new page boundary
1406 offset = RoundUp(offset, kPageSize);
1407 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001408 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001409 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001410 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001411
Ian Rogers848871b2013-08-05 10:56:33 -07001412 #define DO_TRAMPOLINE(field, fn_name) \
1413 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001414 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1415 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001416 (field) = compiler_driver_->Create ## fn_name(); \
1417 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001418
Ian Rogers848871b2013-08-05 10:56:33 -07001419 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001420 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001421 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001422 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1423 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001424
Ian Rogers848871b2013-08-05 10:56:33 -07001425 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001426 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001427 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1428 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1429 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001430 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001431 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001432 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001433 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001434 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001435 return offset;
1436}
1437
1438size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001439 #define VISIT(VisitorType) \
1440 do { \
1441 VisitorType visitor(this, offset); \
1442 bool success = VisitDexMethods(&visitor); \
1443 DCHECK(success); \
1444 offset = visitor.GetOffset(); \
1445 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001446
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001447 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001448 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001449 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001450 }
Logan Chien8b977d32012-02-21 19:14:55 +08001451
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001452 #undef VISIT
1453
Brian Carlstrome24fa612011-09-29 00:53:55 -07001454 return offset;
1455}
1456
David Srbeckybc90fd02015-04-22 19:40:27 +01001457bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001458 CHECK(write_state_ == WriteState::kWriteRoData);
1459
1460 if (!WriteClassOffsets(out)) {
1461 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001462 return false;
1463 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001464
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001465 if (!WriteClasses(out)) {
1466 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001467 return false;
1468 }
1469
Vladimir Markof4da6752014-08-01 19:04:18 +01001470 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001471 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001472 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1473 return false;
1474 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001475 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001476 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001477 relative_offset = WriteMaps(out, file_offset, relative_offset);
1478 if (relative_offset == 0) {
1479 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1480 return false;
1481 }
1482
David Srbeckybc90fd02015-04-22 19:40:27 +01001483 // Write padding.
1484 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1485 relative_offset += size_executable_offset_alignment_;
1486 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1487 size_t expected_file_offset = file_offset + relative_offset;
1488 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1489 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1490 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1491 return 0;
1492 }
1493 DCHECK_OFFSET();
1494
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001495 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001496 return true;
1497}
1498
1499bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001500 CHECK(write_state_ == WriteState::kWriteText);
1501
Vladimir Marko944da602016-02-19 12:27:55 +00001502 SetMultiOatRelativePatcherAdjustment();
1503
David Srbeckybc90fd02015-04-22 19:40:27 +01001504 const size_t file_offset = oat_data_offset_;
1505 size_t relative_offset = oat_header_->GetExecutableOffset();
1506 DCHECK_OFFSET();
1507
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001508 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001509 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001510 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001511 return false;
1512 }
1513
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001514 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1515 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001516 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001517 return false;
1518 }
1519
Vladimir Markof4da6752014-08-01 19:04:18 +01001520 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001521 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001522 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1523 return false;
1524 }
1525
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001526 if (kIsDebugBuild) {
1527 uint32_t size_total = 0;
1528 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001529 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1530 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001531
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001532 DO_STAT(size_dex_file_alignment_);
1533 DO_STAT(size_executable_offset_alignment_);
1534 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001535 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001536 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001537 DO_STAT(size_interpreter_to_interpreter_bridge_);
1538 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1539 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001540 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001541 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001542 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001543 DO_STAT(size_quick_to_interpreter_bridge_);
1544 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001545 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001546 DO_STAT(size_code_);
1547 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001548 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001549 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001550 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001551 DO_STAT(size_oat_dex_file_location_size_);
1552 DO_STAT(size_oat_dex_file_location_data_);
1553 DO_STAT(size_oat_dex_file_location_checksum_);
1554 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001555 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001556 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001557 DO_STAT(size_oat_lookup_table_alignment_);
1558 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001559 DO_STAT(size_oat_class_offsets_alignment_);
1560 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001561 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001562 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001563 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001564 DO_STAT(size_oat_class_method_offsets_);
1565 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001566
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001567 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001568 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001569 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001570 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001571
Vladimir Markof4da6752014-08-01 19:04:18 +01001572 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001573 CHECK_EQ(size_, relative_offset);
1574
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001575 write_state_ = WriteState::kWriteHeader;
1576 return true;
1577}
1578
1579bool OatWriter::WriteHeader(OutputStream* out,
1580 uint32_t image_file_location_oat_checksum,
1581 uintptr_t image_file_location_oat_begin,
1582 int32_t image_patch_delta) {
1583 CHECK(write_state_ == WriteState::kWriteHeader);
1584
1585 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1586 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1587 if (compiler_driver_->IsBootImage()) {
1588 CHECK_EQ(image_patch_delta, 0);
1589 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1590 } else {
1591 CHECK_ALIGNED(image_patch_delta, kPageSize);
1592 oat_header_->SetImagePatchDelta(image_patch_delta);
1593 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001594 oat_header_->UpdateChecksumWithHeaderData();
1595
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001596 const size_t file_offset = oat_data_offset_;
1597
1598 off_t current_offset = out->Seek(0, kSeekCurrent);
1599 if (current_offset == static_cast<off_t>(-1)) {
1600 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1601 return false;
1602 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001603 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001604 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1605 return false;
1606 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001607 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001608
1609 // Flush all other data before writing the header.
1610 if (!out->Flush()) {
1611 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1612 return false;
1613 }
1614 // Write the header.
1615 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001616 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001617 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1618 return false;
1619 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001620 // Flush the header data.
1621 if (!out->Flush()) {
1622 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001623 return false;
1624 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001625
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001626 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1627 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1628 return false;
1629 }
1630 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1631
1632 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001633 return true;
1634}
1635
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001636bool OatWriter::WriteClassOffsets(OutputStream* out) {
1637 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1638 if (oat_dex_file.class_offsets_offset_ != 0u) {
1639 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1640 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1641 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1642 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1643 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001644 return false;
1645 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001646 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1647 return false;
1648 }
1649 }
1650 }
1651 return true;
1652}
1653
1654bool OatWriter::WriteClasses(OutputStream* out) {
1655 for (OatClass& oat_class : oat_classes_) {
1656 if (!oat_class.Write(this, out, oat_data_offset_)) {
1657 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1658 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001659 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001660 }
1661 return true;
1662}
1663
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001664size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001665 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001666 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1667 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1668 return 0;
1669 }
1670 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001671 size_vmap_table_ = relative_offset - vmap_tables_offset;
1672
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001673 return relative_offset;
1674}
1675
1676size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001677 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001678 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001679
Ian Rogers848871b2013-08-05 10:56:33 -07001680 #define DO_TRAMPOLINE(field) \
1681 do { \
1682 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1683 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001684 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001685 size_trampoline_alignment_ += alignment_padding; \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001686 if (!WriteData(out, (field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001687 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001688 return false; \
1689 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001690 size_ ## field += (field)->size(); \
1691 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001692 DCHECK_OFFSET(); \
1693 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001694
Ian Rogers848871b2013-08-05 10:56:33 -07001695 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001696 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001697 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001698 DO_TRAMPOLINE(quick_resolution_trampoline_);
1699 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1700 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001701 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001702 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001703}
1704
Ian Rogers3d504072014-03-01 09:16:49 -08001705size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001706 const size_t file_offset,
1707 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001708 #define VISIT(VisitorType) \
1709 do { \
1710 VisitorType visitor(this, out, file_offset, relative_offset); \
1711 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1712 return 0; \
1713 } \
1714 relative_offset = visitor.GetOffset(); \
1715 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001716
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001717 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001718
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001719 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001720
Vladimir Markob163bb72015-03-31 21:49:49 +01001721 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1722 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1723 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1724
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001725 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001726}
1727
Vladimir Marko944da602016-02-19 12:27:55 +00001728bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001729 // Get the elf file offset of the oat file.
1730 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1731 if (raw_file_offset == static_cast<off_t>(-1)) {
1732 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1733 return false;
1734 }
1735 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1736 return true;
1737}
1738
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001739bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1740 // Read the dex file header and perform minimal verification.
1741 uint8_t raw_header[sizeof(DexFile::Header)];
1742 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1743 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1744 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1745 return false;
1746 }
1747 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1748 return false;
1749 }
1750
1751 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1752 oat_dex_file->dex_file_size_ = header->file_size_;
1753 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1754 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1755 return true;
1756}
1757
1758bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1759 if (!DexFile::IsMagicValid(raw_header)) {
1760 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1761 return false;
1762 }
1763 if (!DexFile::IsVersionValid(raw_header)) {
1764 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1765 return false;
1766 }
1767 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1768 if (header->file_size_ < sizeof(DexFile::Header)) {
1769 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1770 << " File: " << location;
1771 return false;
1772 }
1773 return true;
1774}
1775
1776bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1777 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1778
1779 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001780 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001781 return false;
1782 }
1783
1784 // Write dex files.
1785 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1786 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1787 return false;
1788 }
1789 }
1790
1791 // Close sources.
1792 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1793 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1794 }
1795 zipped_dex_files_.clear();
1796 zip_archives_.clear();
1797 raw_dex_files_.clear();
1798 return true;
1799}
1800
1801bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1802 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1803 return false;
1804 }
1805 if (oat_dex_file->source_.IsZipEntry()) {
1806 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1807 return false;
1808 }
1809 } else if (oat_dex_file->source_.IsRawFile()) {
1810 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1811 return false;
1812 }
1813 } else {
1814 DCHECK(oat_dex_file->source_.IsRawData());
1815 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1816 return false;
1817 }
1818 }
1819
1820 // Update current size and account for the written data.
1821 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1822 size_ += oat_dex_file->dex_file_size_;
1823 size_dex_file_ += oat_dex_file->dex_file_size_;
1824 return true;
1825}
1826
1827bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1828 // Dex files are required to be 4 byte aligned.
1829 size_t original_offset = size_;
1830 size_t offset = RoundUp(original_offset, 4);
1831 size_dex_file_alignment_ += offset - original_offset;
1832
1833 // Seek to the start of the dex file and flush any pending operations in the stream.
1834 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1835 uint32_t start_offset = oat_data_offset_ + offset;
1836 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1837 if (actual_offset != static_cast<off_t>(start_offset)) {
1838 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1839 << " Expected: " << start_offset
1840 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1841 return false;
1842 }
1843 if (!out->Flush()) {
1844 PLOG(ERROR) << "Failed to flush before writing dex file."
1845 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1846 return false;
1847 }
1848 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1849 if (actual_offset != static_cast<off_t>(start_offset)) {
1850 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1851 << " Expected: " << start_offset
1852 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1853 return false;
1854 }
1855
1856 size_ = offset;
1857 oat_dex_file->dex_file_offset_ = offset;
1858 return true;
1859}
1860
1861bool OatWriter::WriteDexFile(OutputStream* rodata,
1862 File* file,
1863 OatDexFile* oat_dex_file,
1864 ZipEntry* dex_file) {
1865 size_t start_offset = oat_data_offset_ + size_;
1866 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1867
1868 // Extract the dex file and get the extracted size.
1869 std::string error_msg;
1870 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1871 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1872 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1873 return false;
1874 }
1875 if (file->Flush() != 0) {
1876 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1877 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1878 return false;
1879 }
1880 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1881 if (extracted_end == static_cast<off_t>(-1)) {
1882 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1883 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1884 return false;
1885 }
1886 if (extracted_end < static_cast<off_t>(start_offset)) {
1887 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1888 << " Start: " << start_offset
1889 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1890 return false;
1891 }
1892 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1893 if (extracted_size < sizeof(DexFile::Header)) {
1894 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1895 << extracted_size << " File: " << oat_dex_file->GetLocation();
1896 return false;
1897 }
1898
1899 // Read the dex file header and extract required data to OatDexFile.
1900 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1901 if (actual_offset != static_cast<off_t>(start_offset)) {
1902 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1903 << " Expected: " << start_offset
1904 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1905 return false;
1906 }
1907 if (!ReadDexFileHeader(file, oat_dex_file)) {
1908 return false;
1909 }
1910 if (extracted_size < oat_dex_file->dex_file_size_) {
1911 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1912 << " file size from header: " << oat_dex_file->dex_file_size_
1913 << " File: " << oat_dex_file->GetLocation();
1914 return false;
1915 }
1916
1917 // Override the checksum from header with the CRC from ZIP entry.
1918 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1919
1920 // Seek both file and stream to the end offset.
1921 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1922 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1923 if (actual_offset != static_cast<off_t>(end_offset)) {
1924 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1925 << " Expected: " << end_offset
1926 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1927 return false;
1928 }
1929 actual_offset = rodata->Seek(end_offset, kSeekSet);
1930 if (actual_offset != static_cast<off_t>(end_offset)) {
1931 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1932 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1933 return false;
1934 }
1935 if (!rodata->Flush()) {
1936 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1937 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1938 return false;
1939 }
1940
1941 // If we extracted more than the size specified in the header, truncate the file.
1942 if (extracted_size > oat_dex_file->dex_file_size_) {
1943 if (file->SetLength(end_offset) != 0) {
1944 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1945 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1946 return false;
1947 }
1948 }
1949
1950 return true;
1951}
1952
1953bool OatWriter::WriteDexFile(OutputStream* rodata,
1954 File* file,
1955 OatDexFile* oat_dex_file,
1956 File* dex_file) {
1957 size_t start_offset = oat_data_offset_ + size_;
1958 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1959
1960 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
1961 if (input_offset != static_cast<off_t>(0)) {
1962 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
1963 << " Expected: 0"
1964 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1965 return false;
1966 }
1967 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
1968 return false;
1969 }
1970
1971 // Copy the input dex file using sendfile().
1972 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
1973 PLOG(ERROR) << "Failed to copy dex file to oat file."
1974 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1975 return false;
1976 }
1977 if (file->Flush() != 0) {
1978 PLOG(ERROR) << "Failed to flush dex file."
1979 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1980 return false;
1981 }
1982
1983 // Check file position and seek the stream to the end offset.
1984 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1985 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1986 if (actual_offset != static_cast<off_t>(end_offset)) {
1987 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
1988 << " Expected: " << end_offset
1989 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1990 return false;
1991 }
1992 actual_offset = rodata->Seek(end_offset, kSeekSet);
1993 if (actual_offset != static_cast<off_t>(end_offset)) {
1994 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1995 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1996 return false;
1997 }
1998 if (!rodata->Flush()) {
1999 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2000 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2001 return false;
2002 }
2003
2004 return true;
2005}
2006
2007bool OatWriter::WriteDexFile(OutputStream* rodata,
2008 OatDexFile* oat_dex_file,
2009 const uint8_t* dex_file) {
2010 // Note: The raw data has already been checked to contain the header
2011 // and all the data that the header specifies as the file size.
2012 DCHECK(dex_file != nullptr);
2013 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2014 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2015
Jeff Haoc3b13a72016-05-23 14:30:44 -07002016 if (!WriteData(rodata, dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002017 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2018 << " to " << rodata->GetLocation();
2019 return false;
2020 }
2021 if (!rodata->Flush()) {
2022 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2023 << " File: " << oat_dex_file->GetLocation();
2024 return false;
2025 }
2026
2027 // Update dex file size and resize class offsets in the OatDexFile.
2028 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2029 oat_dex_file->dex_file_size_ = header->file_size_;
2030 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2031 return true;
2032}
2033
2034bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2035 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2036
2037 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2038 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2039 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2040 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2041 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2042 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2043 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2044 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2045 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2046 return false;
2047 }
2048
2049 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2050 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2051
2052 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2053 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2054
2055 // Write OatDexFile.
2056 if (!oat_dex_file->Write(this, rodata)) {
2057 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2058 return false;
2059 }
2060 }
2061
2062 return true;
2063}
2064
2065bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2066 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2067
2068 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2069 if (file->SetLength(new_length) != 0) {
2070 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2071 << "File: " << file->GetPath();
2072 return false;
2073 }
2074 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2075 if (actual_offset != static_cast<off_t>(new_length)) {
2076 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2077 << " Actual: " << actual_offset << " Expected: " << new_length
2078 << " File: " << rodata->GetLocation();
2079 return false;
2080 }
2081 if (!rodata->Flush()) {
2082 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2083 << " File: " << rodata->GetLocation();
2084 return false;
2085 }
2086 return true;
2087}
2088
2089bool OatWriter::OpenDexFiles(
2090 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002091 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002092 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2093 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2094 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2095
2096 if (oat_dex_files_.empty()) {
2097 // Nothing to do.
2098 return true;
2099 }
2100
2101 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2102 size_t length = size_ - map_offset;
2103 std::string error_msg;
2104 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2105 PROT_READ | PROT_WRITE,
2106 MAP_SHARED,
2107 file->Fd(),
2108 oat_data_offset_ + map_offset,
2109 /* low_4gb */ false,
2110 file->GetPath().c_str(),
2111 &error_msg));
2112 if (dex_files_map == nullptr) {
2113 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2114 << " error: " << error_msg;
2115 return false;
2116 }
2117 std::vector<std::unique_ptr<const DexFile>> dex_files;
2118 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2119 // Make sure no one messed with input files while we were copying data.
2120 // At the very least we need consistent file size and number of class definitions.
2121 const uint8_t* raw_dex_file =
2122 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2123 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2124 // Note: ValidateDexFileHeader() already logged an error message.
2125 LOG(ERROR) << "Failed to verify written dex file header!"
2126 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2127 << " ~ " << static_cast<const void*>(raw_dex_file);
2128 return false;
2129 }
2130 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2131 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2132 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2133 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2134 << " Output: " << file->GetPath();
2135 return false;
2136 }
2137 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2138 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2139 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2140 << " Output: " << file->GetPath();
2141 return false;
2142 }
2143
2144 // Now, open the dex file.
2145 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2146 oat_dex_file.dex_file_size_,
2147 oat_dex_file.GetLocation(),
2148 oat_dex_file.dex_file_location_checksum_,
2149 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002150 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002151 &error_msg));
2152 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002153 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2154 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002155 return false;
2156 }
2157 }
2158
2159 *opened_dex_files_map = std::move(dex_files_map);
2160 *opened_dex_files = std::move(dex_files);
2161 return true;
2162}
2163
2164bool OatWriter::WriteTypeLookupTables(
2165 MemMap* opened_dex_files_map,
2166 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2167 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2168
2169 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2170 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2171 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2172 if (oat_dex_file->lookup_table_offset_ != 0u) {
2173 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2174 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2175 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2176 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2177 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2178 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2179 }
2180 }
2181
2182 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2183 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2184 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2185 return false;
2186 }
2187
2188 return true;
2189}
2190
Vladimir Markof4da6752014-08-01 19:04:18 +01002191bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2192 static const uint8_t kPadding[] = {
2193 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2194 };
2195 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Jeff Haoc3b13a72016-05-23 14:30:44 -07002196 if (UNLIKELY(!WriteData(out, kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002197 return false;
2198 }
2199 size_code_alignment_ += aligned_code_delta;
2200 return true;
2201}
2202
Vladimir Marko49b0f452015-12-10 13:49:19 +00002203bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2204 oat_header_->UpdateChecksum(data, size);
2205 return out->WriteFully(data, size);
2206}
2207
Vladimir Marko944da602016-02-19 12:27:55 +00002208void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2209 DCHECK(dex_files_ != nullptr);
2210 DCHECK(relative_patcher_ != nullptr);
2211 DCHECK_NE(oat_data_offset_, 0u);
2212 if (image_writer_ != nullptr && !dex_files_->empty()) {
2213 // The oat data begin may not be initialized yet but the oat file offset is ready.
2214 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2215 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2216 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002217 }
2218}
2219
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002220OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2221 DexFileSource source,
2222 CreateTypeLookupTable create_type_lookup_table)
2223 : source_(source),
2224 create_type_lookup_table_(create_type_lookup_table),
2225 dex_file_size_(0),
2226 offset_(0),
2227 dex_file_location_size_(strlen(dex_file_location)),
2228 dex_file_location_data_(dex_file_location),
2229 dex_file_location_checksum_(0u),
2230 dex_file_offset_(0u),
2231 class_offsets_offset_(0u),
2232 lookup_table_offset_(0u),
2233 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002234}
2235
2236size_t OatWriter::OatDexFile::SizeOf() const {
2237 return sizeof(dex_file_location_size_)
2238 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002239 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002240 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002241 + sizeof(class_offsets_offset_)
2242 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002243}
2244
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002245void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2246 DCHECK_EQ(lookup_table_offset_, 0u);
2247 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2248 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2249 if (table_size != 0u) {
2250 // Type tables are required to be 4 byte aligned.
2251 size_t original_offset = oat_writer->size_;
2252 size_t offset = RoundUp(original_offset, 4);
2253 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2254 lookup_table_offset_ = offset;
2255 oat_writer->size_ = offset + table_size;
2256 oat_writer->size_oat_lookup_table_ += table_size;
2257 }
2258 }
2259}
2260
2261void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2262 DCHECK_EQ(class_offsets_offset_, 0u);
2263 if (!class_offsets_.empty()) {
2264 // Class offsets are required to be 4 byte aligned.
2265 size_t original_offset = oat_writer->size_;
2266 size_t offset = RoundUp(original_offset, 4);
2267 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2268 class_offsets_offset_ = offset;
2269 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2270 }
2271}
2272
2273bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2274 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002275 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002276
Vladimir Marko49b0f452015-12-10 13:49:19 +00002277 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002278 PLOG(ERROR) << "Failed to write dex file location length 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_size_ += sizeof(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, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002284 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002285 return false;
2286 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002287 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002288
Vladimir Marko49b0f452015-12-10 13:49:19 +00002289 if (!oat_writer->WriteData(out,
2290 &dex_file_location_checksum_,
2291 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002292 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002293 return false;
2294 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002295 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002296
Vladimir Marko49b0f452015-12-10 13:49:19 +00002297 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002298 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002299 return false;
2300 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002301 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002302
2303 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2304 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2305 return false;
2306 }
2307 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2308
Vladimir Marko49b0f452015-12-10 13:49:19 +00002309 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002310 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2311 return false;
2312 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002313 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002314
2315 return true;
2316}
2317
2318bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002319 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002320 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2321 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002322 return false;
2323 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002324 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002325 return true;
2326}
2327
Brian Carlstromba150c32013-08-27 17:31:03 -07002328OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002329 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002330 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002331 mirror::Class::Status status)
2332 : compiled_methods_(compiled_methods) {
2333 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002334 CHECK_LE(num_non_null_compiled_methods, num_methods);
2335
Brian Carlstrom265091e2013-01-30 14:08:26 -08002336 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002337 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2338
2339 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2340 // apply when there are 0 methods, we just arbitrarily say that 0
2341 // methods means kOatClassNoneCompiled and that we won't use
2342 // kOatClassAllCompiled unless there is at least one compiled
2343 // method. This means in an interpretter only system, we can assert
2344 // that all classes are kOatClassNoneCompiled.
2345 if (num_non_null_compiled_methods == 0) {
2346 type_ = kOatClassNoneCompiled;
2347 } else if (num_non_null_compiled_methods == num_methods) {
2348 type_ = kOatClassAllCompiled;
2349 } else {
2350 type_ = kOatClassSomeCompiled;
2351 }
2352
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002353 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002354 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002355 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002356
2357 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2358 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002359 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002360 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2361 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2362 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2363 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002364 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002365 method_bitmap_size_ = 0;
2366 }
2367
2368 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002369 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002370 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002371 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2372 } else {
2373 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2374 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2375 if (type_ == kOatClassSomeCompiled) {
2376 method_bitmap_->SetBit(i);
2377 }
2378 }
2379 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002380}
2381
Brian Carlstrom265091e2013-01-30 14:08:26 -08002382size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2383 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002384 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2385 if (method_offset == 0) {
2386 return 0;
2387 }
2388 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002389}
2390
2391size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2392 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002393 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002394}
2395
2396size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002397 return sizeof(status_)
2398 + sizeof(type_)
2399 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2400 + method_bitmap_size_
2401 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002402}
2403
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002404bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002405 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002406 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002407 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002408 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002409 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002410 return false;
2411 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002412 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002413
2414 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002415 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002416 return false;
2417 }
2418 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002419
Brian Carlstromba150c32013-08-27 17:31:03 -07002420 if (method_bitmap_size_ != 0) {
2421 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002422 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002423 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002424 return false;
2425 }
2426 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002427
2428 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002429 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002430 return false;
2431 }
2432 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2433 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002434
2435 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002436 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002437 return false;
2438 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002439 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002440 return true;
2441}
2442
Brian Carlstrome24fa612011-09-29 00:53:55 -07002443} // namespace art