blob: 96b199ad6e9bd6182dbcb4e79149c4dd5289752a [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
Vladimir Markoe079e212016-05-25 12:49:49 +010066class ChecksumUpdatingOutputStream : public OutputStream {
67 public:
68 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
69 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
70
71 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
72 oat_header_->UpdateChecksum(buffer, byte_count);
73 return out_->WriteFully(buffer, byte_count);
74 }
75
76 off_t Seek(off_t offset, Whence whence) OVERRIDE {
77 return out_->Seek(offset, whence);
78 }
79
80 bool Flush() OVERRIDE {
81 return out_->Flush();
82 }
83
84 private:
85 OutputStream* const out_;
86 OatHeader* const oat_header_;
87};
88
Vladimir Marko0c737df2016-08-01 16:33:16 +010089inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
90 // We want to align the code rather than the preheader.
91 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
92 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
93 return aligned_code_offset - unaligned_code_offset;
94}
95
Vladimir Marko9bdf1082016-01-21 12:15:52 +000096} // anonymous namespace
97
98// Defines the location of the raw dex file to write.
99class OatWriter::DexFileSource {
100 public:
101 explicit DexFileSource(ZipEntry* zip_entry)
102 : type_(kZipEntry), source_(zip_entry) {
103 DCHECK(source_ != nullptr);
104 }
105
106 explicit DexFileSource(File* raw_file)
107 : type_(kRawFile), source_(raw_file) {
108 DCHECK(source_ != nullptr);
109 }
110
111 explicit DexFileSource(const uint8_t* dex_file)
112 : type_(kRawData), source_(dex_file) {
113 DCHECK(source_ != nullptr);
114 }
115
116 bool IsZipEntry() const { return type_ == kZipEntry; }
117 bool IsRawFile() const { return type_ == kRawFile; }
118 bool IsRawData() const { return type_ == kRawData; }
119
120 ZipEntry* GetZipEntry() const {
121 DCHECK(IsZipEntry());
122 DCHECK(source_ != nullptr);
123 return static_cast<ZipEntry*>(const_cast<void*>(source_));
124 }
125
126 File* GetRawFile() const {
127 DCHECK(IsRawFile());
128 DCHECK(source_ != nullptr);
129 return static_cast<File*>(const_cast<void*>(source_));
130 }
131
132 const uint8_t* GetRawData() const {
133 DCHECK(IsRawData());
134 DCHECK(source_ != nullptr);
135 return static_cast<const uint8_t*>(source_);
136 }
137
138 void Clear() {
139 type_ = kNone;
140 source_ = nullptr;
141 }
142
143 private:
144 enum Type {
145 kNone,
146 kZipEntry,
147 kRawFile,
148 kRawData,
149 };
150
151 Type type_;
152 const void* source_;
153};
154
Vladimir Marko49b0f452015-12-10 13:49:19 +0000155class OatWriter::OatClass {
156 public:
157 OatClass(size_t offset,
158 const dchecked_vector<CompiledMethod*>& compiled_methods,
159 uint32_t num_non_null_compiled_methods,
160 mirror::Class::Status status);
161 OatClass(OatClass&& src) = default;
162 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
163 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
164 size_t SizeOf() const;
165 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
166
167 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
168 return compiled_methods_[class_def_method_index];
169 }
170
171 // Offset of start of OatClass from beginning of OatHeader. It is
172 // used to validate file position when writing.
173 size_t offset_;
174
175 // CompiledMethods for each class_def_method_index, or null if no method is available.
176 dchecked_vector<CompiledMethod*> compiled_methods_;
177
178 // Offset from OatClass::offset_ to the OatMethodOffsets for the
179 // class_def_method_index. If 0, it means the corresponding
180 // CompiledMethod entry in OatClass::compiled_methods_ should be
181 // null and that the OatClass::type_ should be kOatClassBitmap.
182 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
183
184 // Data to write.
185
186 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
187 int16_t status_;
188
189 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
190 uint16_t type_;
191
192 uint32_t method_bitmap_size_;
193
194 // bit vector indexed by ClassDef method index. When
195 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
196 // method has an OatMethodOffsets in methods_offsets_, otherwise
197 // the entry was ommited to save space. If OatClassType::type_ is
198 // not is kOatClassBitmap, the bitmap will be null.
199 std::unique_ptr<BitVector> method_bitmap_;
200
201 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
202 // present in the OatClass. Note that some may be missing if
203 // OatClass::compiled_methods_ contains null values (and
204 // oat_method_offsets_offsets_from_oat_class_ should contain 0
205 // values in this case).
206 dchecked_vector<OatMethodOffsets> method_offsets_;
207 dchecked_vector<OatQuickMethodHeader> method_headers_;
208
209 private:
210 size_t GetMethodOffsetsRawSize() const {
211 return method_offsets_.size() * sizeof(method_offsets_[0]);
212 }
213
214 DISALLOW_COPY_AND_ASSIGN(OatClass);
215};
216
217class OatWriter::OatDexFile {
218 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000219 OatDexFile(const char* dex_file_location,
220 DexFileSource source,
221 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000222 OatDexFile(OatDexFile&& src) = default;
223
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000224 const char* GetLocation() const {
225 return dex_file_location_data_;
226 }
227
228 void ReserveTypeLookupTable(OatWriter* oat_writer);
229 void ReserveClassOffsets(OatWriter* oat_writer);
230
Vladimir Marko49b0f452015-12-10 13:49:19 +0000231 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000232 bool Write(OatWriter* oat_writer, OutputStream* out) const;
233 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
234
235 // The source of the dex file.
236 DexFileSource source_;
237
238 // Whether to create the type lookup table.
239 CreateTypeLookupTable create_type_lookup_table_;
240
241 // Dex file size. Initialized when writing the dex file.
242 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000243
244 // Offset of start of OatDexFile from beginning of OatHeader. It is
245 // used to validate file position when writing.
246 size_t offset_;
247
248 // Data to write.
249 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000250 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000251 uint32_t dex_file_location_checksum_;
252 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000253 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000254 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255
256 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000257 dchecked_vector<uint32_t> class_offsets_;
258
259 private:
260 size_t GetClassOffsetsRawSize() const {
261 return class_offsets_.size() * sizeof(class_offsets_[0]);
262 }
263
264 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
265};
266
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100267#define DCHECK_OFFSET() \
268 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
269 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
270
271#define DCHECK_OFFSET_() \
272 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
273 << "file_offset=" << file_offset << " offset_=" << offset_
274
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000275OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
276 : write_state_(WriteState::kAddingDexFileSources),
277 timings_(timings),
278 raw_dex_files_(),
279 zip_archives_(),
280 zipped_dex_files_(),
281 zipped_dex_file_locations_(),
282 compiler_driver_(nullptr),
283 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800284 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000285 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100286 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000287 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100288 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700289 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700290 size_dex_file_alignment_(0),
291 size_executable_offset_alignment_(0),
292 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700293 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700294 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700295 size_interpreter_to_interpreter_bridge_(0),
296 size_interpreter_to_compiled_code_bridge_(0),
297 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800298 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700299 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700300 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700301 size_quick_to_interpreter_bridge_(0),
302 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100303 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700304 size_code_(0),
305 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100306 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100307 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700308 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_oat_dex_file_location_size_(0),
310 size_oat_dex_file_location_data_(0),
311 size_oat_dex_file_location_checksum_(0),
312 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000313 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000314 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000315 size_oat_lookup_table_alignment_(0),
316 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000317 size_oat_class_offsets_alignment_(0),
318 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700319 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700320 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700321 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100322 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000323 relative_patcher_(nullptr),
324 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000325}
326
327bool OatWriter::AddDexFileSource(const char* filename,
328 const char* location,
329 CreateTypeLookupTable create_type_lookup_table) {
330 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
331 uint32_t magic;
332 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700333 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
334 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000335 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
336 return false;
337 } else if (IsDexMagic(magic)) {
338 // The file is open for reading, not writing, so it's OK to let the File destructor
339 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700340 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000341 oat_dex_files_.emplace_back(location,
342 DexFileSource(raw_dex_files_.back().get()),
343 create_type_lookup_table);
344 } else if (IsZipMagic(magic)) {
345 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
346 return false;
347 }
348 } else {
349 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
350 return false;
351 }
352 return true;
353}
354
355// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700356bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000357 const char* location,
358 CreateTypeLookupTable create_type_lookup_table) {
359 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
360 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700361 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000362 ZipArchive* zip_archive = zip_archives_.back().get();
363 if (zip_archive == nullptr) {
364 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
365 << error_msg;
366 return false;
367 }
368 for (size_t i = 0; ; ++i) {
369 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
370 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
371 if (entry == nullptr) {
372 break;
373 }
374 zipped_dex_files_.push_back(std::move(entry));
375 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
376 const char* full_location = zipped_dex_file_locations_.back().c_str();
377 oat_dex_files_.emplace_back(full_location,
378 DexFileSource(zipped_dex_files_.back().get()),
379 create_type_lookup_table);
380 }
381 if (zipped_dex_file_locations_.empty()) {
382 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
383 return false;
384 }
385 return true;
386}
387
388// Add dex file source from raw memory.
389bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
390 const char* location,
391 uint32_t location_checksum,
392 CreateTypeLookupTable create_type_lookup_table) {
393 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
394 if (data.size() < sizeof(DexFile::Header)) {
395 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
396 << data.size() << " File: " << location;
397 return false;
398 }
399 if (!ValidateDexFileHeader(data.data(), location)) {
400 return false;
401 }
402 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
403 if (data.size() < header->file_size_) {
404 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
405 << " file size from header: " << header->file_size_ << " File: " << location;
406 return false;
407 }
408
409 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
410 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
411 return true;
412}
413
414dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
415 dchecked_vector<const char*> locations;
416 locations.reserve(oat_dex_files_.size());
417 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
418 locations.push_back(oat_dex_file.GetLocation());
419 }
420 return locations;
421}
422
423bool OatWriter::WriteAndOpenDexFiles(
424 OutputStream* rodata,
425 File* file,
426 InstructionSet instruction_set,
427 const InstructionSetFeatures* instruction_set_features,
428 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800429 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000430 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
431 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
432 CHECK(write_state_ == WriteState::kAddingDexFileSources);
433
434 size_t offset = InitOatHeader(instruction_set,
435 instruction_set_features,
436 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
437 key_value_store);
438 offset = InitOatDexFiles(offset);
439 size_ = offset;
440
441 std::unique_ptr<MemMap> dex_files_map;
442 std::vector<std::unique_ptr<const DexFile>> dex_files;
443 if (!WriteDexFiles(rodata, file)) {
444 return false;
445 }
446 // Reserve space for type lookup tables and update type_lookup_table_offset_.
447 for (OatDexFile& oat_dex_file : oat_dex_files_) {
448 oat_dex_file.ReserveTypeLookupTable(this);
449 }
450 size_t size_after_type_lookup_tables = size_;
451 // Reserve space for class offsets and update class_offsets_offset_.
452 for (OatDexFile& oat_dex_file : oat_dex_files_) {
453 oat_dex_file.ReserveClassOffsets(this);
454 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100455 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
456 if (!WriteOatDexFiles(&checksum_updating_rodata) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000457 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800458 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000459 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
460 return false;
461 }
462
Vladimir Markoe079e212016-05-25 12:49:49 +0100463 // Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
464 // piece would be difficult because we're not using the OutpuStream directly.
465 if (!oat_dex_files_.empty()) {
466 size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
467 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
468 }
469
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000470 *opened_dex_files_map = std::move(dex_files_map);
471 *opened_dex_files = std::move(dex_files);
472 write_state_ = WriteState::kPrepareLayout;
473 return true;
474}
475
476void OatWriter::PrepareLayout(const CompilerDriver* compiler,
477 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000478 const std::vector<const DexFile*>& dex_files,
479 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480 CHECK(write_state_ == WriteState::kPrepareLayout);
481
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000482 compiler_driver_ = compiler;
483 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000484 dex_files_ = &dex_files;
485 relative_patcher_ = relative_patcher;
486 SetMultiOatRelativePatcherAdjustment();
487
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 if (compiling_boot_image_) {
489 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800490 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100491 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100493
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000494 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800495 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000496 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800497 offset = InitOatClasses(offset);
498 }
499 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000500 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100501 offset = InitOatMaps(offset);
502 }
503 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000504 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800505 offset = InitOatCode(offset);
506 }
507 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000508 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800509 offset = InitOatCodeDexFiles(offset);
510 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700511 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700512
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800513 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100514 // Allocate space for app dex cache arrays in the .bss section.
515 size_t bss_start = RoundUp(size_, kPageSize);
516 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
517 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000518 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100519 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
520 DexCacheArraysLayout layout(pointer_size, dex_file);
521 bss_size_ += layout.Size();
522 }
523 }
524
Brian Carlstrome24fa612011-09-29 00:53:55 -0700525 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800526 if (compiling_boot_image_) {
527 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000528 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800529 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530
531 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700532}
533
Ian Rogers0571d352011-11-03 19:51:38 -0700534OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700535}
536
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100537class OatWriter::DexMethodVisitor {
538 public:
539 DexMethodVisitor(OatWriter* writer, size_t offset)
540 : writer_(writer),
541 offset_(offset),
542 dex_file_(nullptr),
543 class_def_index_(DexFile::kDexNoIndex) {
544 }
545
546 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
547 DCHECK(dex_file_ == nullptr);
548 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
549 dex_file_ = dex_file;
550 class_def_index_ = class_def_index;
551 return true;
552 }
553
554 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
555
556 virtual bool EndClass() {
557 if (kIsDebugBuild) {
558 dex_file_ = nullptr;
559 class_def_index_ = DexFile::kDexNoIndex;
560 }
561 return true;
562 }
563
564 size_t GetOffset() const {
565 return offset_;
566 }
567
568 protected:
569 virtual ~DexMethodVisitor() { }
570
571 OatWriter* const writer_;
572
573 // The offset is usually advanced for each visited method by the derived class.
574 size_t offset_;
575
576 // The dex file and class def index are set in StartClass().
577 const DexFile* dex_file_;
578 size_t class_def_index_;
579};
580
581class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
582 public:
583 OatDexMethodVisitor(OatWriter* writer, size_t offset)
584 : DexMethodVisitor(writer, offset),
585 oat_class_index_(0u),
586 method_offsets_index_(0u) {
587 }
588
589 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
590 DexMethodVisitor::StartClass(dex_file, class_def_index);
591 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
592 method_offsets_index_ = 0u;
593 return true;
594 }
595
596 bool EndClass() {
597 ++oat_class_index_;
598 return DexMethodVisitor::EndClass();
599 }
600
601 protected:
602 size_t oat_class_index_;
603 size_t method_offsets_index_;
604};
605
606class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
607 public:
608 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
609 : DexMethodVisitor(writer, offset),
610 compiled_methods_(),
611 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000612 size_t num_classes = 0u;
613 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
614 num_classes += oat_dex_file.class_offsets_.size();
615 }
616 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100617 compiled_methods_.reserve(256u);
618 }
619
620 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
621 DexMethodVisitor::StartClass(dex_file, class_def_index);
622 compiled_methods_.clear();
623 num_non_null_compiled_methods_ = 0u;
624 return true;
625 }
626
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300627 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
628 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100629 // Fill in the compiled_methods_ array for methods that have a
630 // CompiledMethod. We track the number of non-null entries in
631 // num_non_null_compiled_methods_ since we only want to allocate
632 // OatMethodOffsets for the compiled methods.
633 uint32_t method_idx = it.GetMemberIndex();
634 CompiledMethod* compiled_method =
635 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
636 compiled_methods_.push_back(compiled_method);
637 if (compiled_method != nullptr) {
638 ++num_non_null_compiled_methods_;
639 }
640 return true;
641 }
642
643 bool EndClass() {
644 ClassReference class_ref(dex_file_, class_def_index_);
645 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
646 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700647 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100648 status = compiled_class->GetStatus();
649 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
650 status = mirror::Class::kStatusError;
651 } else {
652 status = mirror::Class::kStatusNotReady;
653 }
654
Vladimir Marko49b0f452015-12-10 13:49:19 +0000655 writer_->oat_classes_.emplace_back(offset_,
656 compiled_methods_,
657 num_non_null_compiled_methods_,
658 status);
659 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100660 return DexMethodVisitor::EndClass();
661 }
662
663 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000664 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100665 size_t num_non_null_compiled_methods_;
666};
667
668class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
669 public:
670 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100671 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100672 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100673 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100674 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
675 }
676
677 bool EndClass() {
678 OatDexMethodVisitor::EndClass();
679 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100680 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100681 }
682 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100683 }
684
685 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700686 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000687 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100688 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
689
690 if (compiled_method != nullptr) {
691 // Derived from CompiledMethod.
692 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100693
Vladimir Marko35831e82015-09-11 11:59:18 +0100694 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
695 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800696 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800697
David Srbecky009e2a62015-04-15 02:46:30 +0100698 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100699 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800700 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000701 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000702 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
703 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800704 // Duplicate methods, we want the same code for both of them so that the oat writer puts
705 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800706 } else {
707 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100708 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800709 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000710 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100711 quick_code_offset = dedupe_map_.GetOrCreate(
712 compiled_method,
713 [this, &deduped, compiled_method, &it, thumb_offset]() {
714 deduped = false;
715 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
716 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800717 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100719 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000720 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100721 // TODO: Should this be a hard failure?
722 LOG(WARNING) << "Multiple definitions of "
723 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000724 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
725 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100726 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000727 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100728 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800729 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100730
Elliott Hughes956af0f2014-12-11 14:34:28 -0800731 // Update quick method header.
732 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
733 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800734 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100735 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
736 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100737 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800738 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
739 // to 0-offset and we need to adjust it by code_offset.
740 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100741 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800742 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100743 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800744 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800745 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
746 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
747 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100748 *method_header = OatQuickMethodHeader(vmap_table_offset,
749 frame_size_in_bytes,
750 core_spill_mask,
751 fp_spill_mask,
752 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100753
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000754 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800755 // Update offsets. (Checksum is updated when writing.)
756 offset_ += sizeof(*method_header); // Method header is prepended before code.
757 offset_ += code_size;
758 // Record absolute patch locations.
759 if (!compiled_method->GetPatches().empty()) {
760 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
761 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000762 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100763 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100764 }
765 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100766 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800767 }
Alex Light78382fa2014-06-06 15:45:32 -0700768
David Srbecky91cc06c2016-03-07 16:13:58 +0000769 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000770 // Exclude quickened dex methods (code_size == 0) since they have no native code.
771 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
772 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800773 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000774 debug::MethodDebugInfo info = debug::MethodDebugInfo();
775 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000776 info.dex_file = dex_file_;
777 info.class_def_index = class_def_index_;
778 info.dex_method_index = it.GetMemberIndex();
779 info.access_flags = it.GetMethodAccessFlags();
780 info.code_item = it.GetMethodCodeItem();
781 info.isa = compiled_method->GetInstructionSet();
782 info.deduped = deduped;
783 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
784 info.is_optimized = method_header->IsOptimized();
785 info.is_code_address_text_relative = true;
786 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
787 info.code_size = code_size;
788 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
789 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
790 info.cfi = compiled_method->GetCFIInfo();
791 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100792 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100793
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
795 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
796 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100797 ++method_offsets_index_;
798 }
799
800 return true;
801 }
802
803 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000804 struct CodeOffsetsKeyComparator {
805 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100806 // Code is deduplicated by CompilerDriver, compare only data pointers.
807 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
808 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000809 }
810 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100811 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
812 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000813 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100814 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
815 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000816 }
817 return false;
818 }
819 };
820
David Srbecky009e2a62015-04-15 02:46:30 +0100821 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
822 const ClassDataItemIterator& it,
823 uint32_t thumb_offset) {
824 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100825 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100826 offset_ += CodeAlignmentSize(offset_, *compiled_method);
827 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100828 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
829 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
830 }
831
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832 // Deduplication is already done on a pointer basis by the compiler driver,
833 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100834 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100835
David Srbecky009e2a62015-04-15 02:46:30 +0100836 // Cache of compiler's --debuggable option.
837 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100838};
839
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100840class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
841 public:
842 InitMapMethodVisitor(OatWriter* writer, size_t offset)
843 : OatDexMethodVisitor(writer, offset) {
844 }
845
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700846 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700847 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000848 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100849 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
850
851 if (compiled_method != nullptr) {
852 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100853 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100854
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100855 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100856 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100857 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100858 size_t offset = dedupe_map_.GetOrCreate(
859 map.data(),
860 [this, map_size]() {
861 uint32_t new_offset = offset_;
862 offset_ += map_size;
863 return new_offset;
864 });
865 // Code offset is not initialized yet, so set the map offset to 0u-offset.
866 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
867 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100868 }
869 ++method_offsets_index_;
870 }
871
872 return true;
873 }
874
875 private:
876 // Deduplication is already done on a pointer basis by the compiler driver,
877 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100878 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100879};
880
881class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
882 public:
883 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800884 : OatDexMethodVisitor(writer, offset),
885 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100886 }
887
888 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700889 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800890 const DexFile::TypeId& type_id =
891 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
892 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
893 // Skip methods that are not in the image.
894 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
895 return true;
896 }
897
Vladimir Marko49b0f452015-12-10 13:49:19 +0000898 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100899 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
900
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800901 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100902 if (compiled_method != nullptr) {
903 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
904 offsets = oat_class->method_offsets_[method_offsets_index_];
905 ++method_offsets_index_;
906 }
907
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100908 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100909 // Unchecked as we hold mutator_lock_ on entry.
910 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800911 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700912 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
913 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800914 ArtMethod* method;
915 if (writer_->HasBootImage()) {
916 const InvokeType invoke_type = it.GetMethodInvokeType(
917 dex_file_->GetClassDef(class_def_index_));
918 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
919 *dex_file_,
920 it.GetMemberIndex(),
921 dex_cache,
922 ScopedNullHandle<mirror::ClassLoader>(),
923 nullptr,
924 invoke_type);
925 if (method == nullptr) {
926 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
927 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
928 soa.Self()->AssertPendingException();
929 mirror::Throwable* exc = soa.Self()->GetException();
930 std::string dump = exc->Dump();
931 LOG(FATAL) << dump;
932 UNREACHABLE();
933 }
934 } else {
935 // Should already have been resolved by the compiler, just peek into the dex cache.
936 // It may not be resolved if the class failed to verify, in this case, don't set the
937 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
938 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700939 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800940 if (method != nullptr &&
941 compiled_method != nullptr &&
942 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100943 method->SetEntryPointFromQuickCompiledCodePtrSize(
944 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
945 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946
947 return true;
948 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800949
950 protected:
951 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952};
953
954class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
955 public:
956 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100957 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100958 : OatDexMethodVisitor(writer, relative_offset),
959 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100960 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100961 soa_(Thread::Current()),
962 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100963 class_linker_(Runtime::Current()->GetClassLinker()),
964 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100965 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800966 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100967 // If we're creating the image, the address space must be ready so that we can apply patches.
968 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100969 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100970 }
971
Vladimir Markof4da6752014-08-01 19:04:18 +0100972 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100973 }
974
975 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700976 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100977 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
978 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700979 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000980 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100981 }
982 return true;
983 }
984
Mathieu Chartier90443472015-07-16 20:32:27 -0700985 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100986 bool result = OatDexMethodVisitor::EndClass();
987 if (oat_class_index_ == writer_->oat_classes_.size()) {
988 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000989 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100990 if (UNLIKELY(offset_ == 0u)) {
991 PLOG(ERROR) << "Failed to write final relative call thunks";
992 result = false;
993 }
994 }
995 return result;
996 }
997
998 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700999 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001000 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001001 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1002
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001003 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1004 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001005 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001006 size_t file_offset = file_offset_;
1007 OutputStream* out = out_;
1008
Vladimir Marko35831e82015-09-11 11:59:18 +01001009 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1010 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001011
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001012 // Deduplicate code arrays.
1013 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1014 if (method_offsets.code_offset_ > offset_) {
1015 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1016 if (offset_ == 0u) {
1017 ReportWriteFailure("relative call thunk", it);
1018 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001019 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001020 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1021 if (alignment_size != 0) {
1022 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001023 ReportWriteFailure("code alignment padding", it);
1024 return false;
1025 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001026 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001027 DCHECK_OFFSET_();
1028 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001029 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001030 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1031 DCHECK_EQ(method_offsets.code_offset_,
1032 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1033 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1034 const OatQuickMethodHeader& method_header =
1035 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001036 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001037 ReportWriteFailure("method header", it);
1038 return false;
1039 }
1040 writer_->size_method_header_ += sizeof(method_header);
1041 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001042 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001043
1044 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001045 patched_code_.assign(quick_code.begin(), quick_code.end());
1046 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001047 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001048 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001049 switch (patch.GetType()) {
1050 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001051 // NOTE: Relative calls across oat files are not supported.
1052 uint32_t target_offset = GetTargetOffset(patch);
1053 writer_->relative_patcher_->PatchCall(&patched_code_,
1054 literal_offset,
1055 offset_ + literal_offset,
1056 target_offset);
1057 break;
1058 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001059 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001060 uint32_t target_offset = GetDexCacheOffset(patch);
1061 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1062 patch,
1063 offset_ + literal_offset,
1064 target_offset);
1065 break;
1066 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001067 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001068 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1069 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1070 patch,
1071 offset_ + literal_offset,
1072 target_offset);
1073 break;
1074 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001075 case LinkerPatch::Type::kTypeRelative: {
1076 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1077 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1078 patch,
1079 offset_ + literal_offset,
1080 target_offset);
1081 break;
1082 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001083 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001084 uint32_t target_offset = GetTargetOffset(patch);
1085 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1086 break;
1087 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001088 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001089 ArtMethod* method = GetTargetMethod(patch);
1090 PatchMethodAddress(&patched_code_, literal_offset, method);
1091 break;
1092 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001093 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001094 mirror::String* string = GetTargetString(patch);
1095 PatchObjectAddress(&patched_code_, literal_offset, string);
1096 break;
1097 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001098 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001099 mirror::Class* type = GetTargetType(patch);
1100 PatchObjectAddress(&patched_code_, literal_offset, type);
1101 break;
1102 }
1103 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001104 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001105 break;
1106 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001107 }
1108 }
1109 }
1110
Vladimir Markoe079e212016-05-25 12:49:49 +01001111 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001112 ReportWriteFailure("method code", it);
1113 return false;
1114 }
1115 writer_->size_code_ += code_size;
1116 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001117 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001118 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001119 ++method_offsets_index_;
1120 }
1121
1122 return true;
1123 }
1124
1125 private:
1126 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001127 const size_t file_offset_;
1128 const ScopedObjectAccess soa_;
1129 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001130 ClassLinker* const class_linker_;
1131 mirror::DexCache* dex_cache_;
1132 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001133
1134 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1135 PLOG(ERROR) << "Failed to write " << what << " for "
1136 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1137 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001138
Mathieu Chartiere401d142015-04-22 13:56:20 -07001139 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001140 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001141 MethodReference ref = patch.TargetMethod();
1142 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001143 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1144 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001145 ArtMethod* method = dex_cache->GetResolvedMethod(
1146 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001147 CHECK(method != nullptr);
1148 return method;
1149 }
1150
Mathieu Chartier90443472015-07-16 20:32:27 -07001151 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001152 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1153 // If there's no new compiled code, either we're compiling an app and the target method
1154 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001155 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001156 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001157 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001158 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1159 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1160 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001161 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001162 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1163 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1164 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1165 target_offset = PointerToLowMemUInt32(oat_code_offset);
1166 } else {
1167 target_offset = target->IsNative()
1168 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1169 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1170 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001171 }
1172 return target_offset;
1173 }
1174
Vladimir Marko052164a2016-04-27 13:54:18 +01001175 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
1176 SHARED_REQUIRES(Locks::mutator_lock_) {
1177 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001178 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001179 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1180 }
1181
1182 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1183 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001184 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1185 CHECK(type != nullptr);
1186 return type;
1187 }
1188
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001189 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001190 mirror::DexCache* dex_cache = GetDexCache(patch.TargetStringDexFile());
1191 mirror::String* string = dex_cache->GetResolvedString(patch.TargetStringIndex());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001192 DCHECK(string != nullptr);
1193 DCHECK(writer_->HasBootImage() ||
1194 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1195 return string;
1196 }
1197
Mathieu Chartier90443472015-07-16 20:32:27 -07001198 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001199 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001200 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1201 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1202 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1203 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001204 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001205 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001206 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1207 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001208 }
1209 }
1210
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001211 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1212 DCHECK(writer_->HasBootImage());
1213 object = writer_->image_writer_->GetImageAddress(object);
1214 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1215 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1216 // TODO: Clean up offset types. The target offset must be treated as signed.
1217 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1218 }
1219
Vladimir Markof4da6752014-08-01 19:04:18 +01001220 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001221 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001222 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001223 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001224 } else {
1225 // NOTE: We're using linker patches for app->boot references when the image can
1226 // be relocated and therefore we need to emit .oat_patches. We're not using this
1227 // for app->app references, so check that the object is in the image space.
1228 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001229 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001230 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001231 uint32_t address = PointerToLowMemUInt32(object);
1232 DCHECK_LE(offset + 4, code->size());
1233 uint8_t* data = &(*code)[offset];
1234 data[0] = address & 0xffu;
1235 data[1] = (address >> 8) & 0xffu;
1236 data[2] = (address >> 16) & 0xffu;
1237 data[3] = (address >> 24) & 0xffu;
1238 }
1239
Mathieu Chartiere401d142015-04-22 13:56:20 -07001240 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001241 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001242 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001244 } else if (kIsDebugBuild) {
1245 // NOTE: We're using linker patches for app->boot references when the image can
1246 // be relocated and therefore we need to emit .oat_patches. We're not using this
1247 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001248 std::vector<gc::space::ImageSpace*> image_spaces =
1249 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1250 bool contains_method = false;
1251 for (gc::space::ImageSpace* image_space : image_spaces) {
1252 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1253 contains_method |=
1254 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1255 }
1256 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001257 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001258 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001259 uint32_t address = PointerToLowMemUInt32(method);
1260 DCHECK_LE(offset + 4, code->size());
1261 uint8_t* data = &(*code)[offset];
1262 data[0] = address & 0xffu;
1263 data[1] = (address >> 8) & 0xffu;
1264 data[2] = (address >> 16) & 0xffu;
1265 data[3] = (address >> 24) & 0xffu;
1266 }
1267
Vladimir Markof4da6752014-08-01 19:04:18 +01001268 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001269 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001270 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001271 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001272 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1273 // TODO: Clean up offset types.
1274 // The target_offset must be treated as signed for cross-oat patching.
1275 const void* target = reinterpret_cast<const void*>(
1276 writer_->image_writer_->GetOatDataBegin(oat_index) +
1277 static_cast<int32_t>(target_offset));
1278 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001279 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001280 DCHECK_LE(offset + 4, code->size());
1281 uint8_t* data = &(*code)[offset];
1282 data[0] = address & 0xffu;
1283 data[1] = (address >> 8) & 0xffu;
1284 data[2] = (address >> 16) & 0xffu;
1285 data[3] = (address >> 24) & 0xffu;
1286 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001287};
1288
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001289class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1290 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001291 WriteMapMethodVisitor(OatWriter* writer,
1292 OutputStream* out,
1293 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001294 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001295 : OatDexMethodVisitor(writer, relative_offset),
1296 out_(out),
1297 file_offset_(file_offset) {
1298 }
1299
1300 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001301 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001302 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1303
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001304 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001305 size_t file_offset = file_offset_;
1306 OutputStream* out = out_;
1307
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001308 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1309 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001310 ++method_offsets_index_;
1311
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001312 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1313 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1314 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1315 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1316
1317 if (map_offset != 0u) {
1318 // Transform map_offset to actual oat data offset.
1319 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1320 DCHECK_NE(map_offset, 0u);
1321 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1322
1323 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1324 size_t map_size = map.size() * sizeof(map[0]);
1325 if (map_offset == offset_) {
1326 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001327 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001328 ReportWriteFailure(it);
1329 return false;
1330 }
1331 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001332 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001333 }
1334 DCHECK_OFFSET_();
1335 }
1336
1337 return true;
1338 }
1339
1340 private:
1341 OutputStream* const out_;
1342 size_t const file_offset_;
1343
1344 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001345 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001346 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1347 }
1348};
1349
1350// Visit all methods from all classes in all dex files with the specified visitor.
1351bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1352 for (const DexFile* dex_file : *dex_files_) {
1353 const size_t class_def_count = dex_file->NumClassDefs();
1354 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1355 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1356 return false;
1357 }
1358 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001359 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001360 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001361 ClassDataItemIterator it(*dex_file, class_data);
1362 while (it.HasNextStaticField()) {
1363 it.Next();
1364 }
1365 while (it.HasNextInstanceField()) {
1366 it.Next();
1367 }
1368 size_t class_def_method_index = 0u;
1369 while (it.HasNextDirectMethod()) {
1370 if (!visitor->VisitMethod(class_def_method_index, it)) {
1371 return false;
1372 }
1373 ++class_def_method_index;
1374 it.Next();
1375 }
1376 while (it.HasNextVirtualMethod()) {
1377 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1378 return false;
1379 }
1380 ++class_def_method_index;
1381 it.Next();
1382 }
1383 }
1384 if (UNLIKELY(!visitor->EndClass())) {
1385 return false;
1386 }
1387 }
1388 }
1389 return true;
1390}
1391
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001392size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1393 const InstructionSetFeatures* instruction_set_features,
1394 uint32_t num_dex_files,
1395 SafeMap<std::string, std::string>* key_value_store) {
1396 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1397 oat_header_.reset(OatHeader::Create(instruction_set,
1398 instruction_set_features,
1399 num_dex_files,
1400 key_value_store));
1401 size_oat_header_ += sizeof(OatHeader);
1402 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001403 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001404}
1405
1406size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001407 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1408 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001409 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001410 oat_dex_file.offset_ = offset;
1411 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001412 }
1413 return offset;
1414}
1415
Brian Carlstrom389efb02012-01-11 12:06:26 -08001416size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001417 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001418 InitOatClassesMethodVisitor visitor(this, offset);
1419 bool success = VisitDexMethods(&visitor);
1420 CHECK(success);
1421 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001422
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 // Update oat_dex_files_.
1424 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001425 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1426 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001427 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001428 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001429 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001430 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001431 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001432 CHECK(oat_class_it == oat_classes_.end());
1433
1434 return offset;
1435}
1436
1437size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001438 InitMapMethodVisitor visitor(this, offset);
1439 bool success = VisitDexMethods(&visitor);
1440 DCHECK(success);
1441 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001442
Brian Carlstrome24fa612011-09-29 00:53:55 -07001443 return offset;
1444}
1445
1446size_t OatWriter::InitOatCode(size_t offset) {
1447 // calculate the offsets within OatHeader to executable code
1448 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001449 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001450 // required to be on a new page boundary
1451 offset = RoundUp(offset, kPageSize);
1452 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001453 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001454 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001455 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001456
Ian Rogers848871b2013-08-05 10:56:33 -07001457 #define DO_TRAMPOLINE(field, fn_name) \
1458 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001459 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1460 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001461 (field) = compiler_driver_->Create ## fn_name(); \
1462 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001463
Ian Rogers848871b2013-08-05 10:56:33 -07001464 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001465 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001466 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001467 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1468 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001469
Ian Rogers848871b2013-08-05 10:56:33 -07001470 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001471 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001472 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1473 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1474 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001475 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001476 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001477 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001478 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001479 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001480 return offset;
1481}
1482
1483size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001484 #define VISIT(VisitorType) \
1485 do { \
1486 VisitorType visitor(this, offset); \
1487 bool success = VisitDexMethods(&visitor); \
1488 DCHECK(success); \
1489 offset = visitor.GetOffset(); \
1490 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001491
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001492 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001493 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001494 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001495 }
Logan Chien8b977d32012-02-21 19:14:55 +08001496
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001497 #undef VISIT
1498
Brian Carlstrome24fa612011-09-29 00:53:55 -07001499 return offset;
1500}
1501
David Srbeckybc90fd02015-04-22 19:40:27 +01001502bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001503 CHECK(write_state_ == WriteState::kWriteRoData);
1504
Vladimir Markoe079e212016-05-25 12:49:49 +01001505 // Wrap out to update checksum with each write.
1506 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1507 out = &checksum_updating_out;
1508
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001509 if (!WriteClassOffsets(out)) {
1510 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001511 return false;
1512 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001513
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001514 if (!WriteClasses(out)) {
1515 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001516 return false;
1517 }
1518
Vladimir Markof4da6752014-08-01 19:04:18 +01001519 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001520 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001521 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1522 return false;
1523 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001524 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001525 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001526 relative_offset = WriteMaps(out, file_offset, relative_offset);
1527 if (relative_offset == 0) {
1528 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1529 return false;
1530 }
1531
David Srbeckybc90fd02015-04-22 19:40:27 +01001532 // Write padding.
1533 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1534 relative_offset += size_executable_offset_alignment_;
1535 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1536 size_t expected_file_offset = file_offset + relative_offset;
1537 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1538 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1539 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1540 return 0;
1541 }
1542 DCHECK_OFFSET();
1543
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001544 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001545 return true;
1546}
1547
1548bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001549 CHECK(write_state_ == WriteState::kWriteText);
1550
Vladimir Markoe079e212016-05-25 12:49:49 +01001551 // Wrap out to update checksum with each write.
1552 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1553 out = &checksum_updating_out;
1554
Vladimir Marko944da602016-02-19 12:27:55 +00001555 SetMultiOatRelativePatcherAdjustment();
1556
David Srbeckybc90fd02015-04-22 19:40:27 +01001557 const size_t file_offset = oat_data_offset_;
1558 size_t relative_offset = oat_header_->GetExecutableOffset();
1559 DCHECK_OFFSET();
1560
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001561 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001562 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001563 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001564 return false;
1565 }
1566
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001567 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1568 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001569 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001570 return false;
1571 }
1572
Vladimir Markof4da6752014-08-01 19:04:18 +01001573 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001574 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001575 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1576 return false;
1577 }
1578
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001579 if (kIsDebugBuild) {
1580 uint32_t size_total = 0;
1581 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001582 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1583 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001584
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001585 DO_STAT(size_dex_file_alignment_);
1586 DO_STAT(size_executable_offset_alignment_);
1587 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001588 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001589 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001590 DO_STAT(size_interpreter_to_interpreter_bridge_);
1591 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1592 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001593 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001594 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001595 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001596 DO_STAT(size_quick_to_interpreter_bridge_);
1597 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001598 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001599 DO_STAT(size_code_);
1600 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001601 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001602 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001603 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001604 DO_STAT(size_oat_dex_file_location_size_);
1605 DO_STAT(size_oat_dex_file_location_data_);
1606 DO_STAT(size_oat_dex_file_location_checksum_);
1607 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001608 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001609 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001610 DO_STAT(size_oat_lookup_table_alignment_);
1611 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001612 DO_STAT(size_oat_class_offsets_alignment_);
1613 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001614 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001615 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001616 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001617 DO_STAT(size_oat_class_method_offsets_);
1618 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001619
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001620 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001621 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001622 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001623 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001624
Vladimir Markof4da6752014-08-01 19:04:18 +01001625 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001626 CHECK_EQ(size_, relative_offset);
1627
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001628 write_state_ = WriteState::kWriteHeader;
1629 return true;
1630}
1631
1632bool OatWriter::WriteHeader(OutputStream* out,
1633 uint32_t image_file_location_oat_checksum,
1634 uintptr_t image_file_location_oat_begin,
1635 int32_t image_patch_delta) {
1636 CHECK(write_state_ == WriteState::kWriteHeader);
1637
1638 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1639 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1640 if (compiler_driver_->IsBootImage()) {
1641 CHECK_EQ(image_patch_delta, 0);
1642 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1643 } else {
1644 CHECK_ALIGNED(image_patch_delta, kPageSize);
1645 oat_header_->SetImagePatchDelta(image_patch_delta);
1646 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001647 oat_header_->UpdateChecksumWithHeaderData();
1648
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001649 const size_t file_offset = oat_data_offset_;
1650
1651 off_t current_offset = out->Seek(0, kSeekCurrent);
1652 if (current_offset == static_cast<off_t>(-1)) {
1653 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1654 return false;
1655 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001656 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001657 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1658 return false;
1659 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001660 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001661
1662 // Flush all other data before writing the header.
1663 if (!out->Flush()) {
1664 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1665 return false;
1666 }
1667 // Write the header.
1668 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001669 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001670 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1671 return false;
1672 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001673 // Flush the header data.
1674 if (!out->Flush()) {
1675 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001676 return false;
1677 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001678
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001679 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1680 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1681 return false;
1682 }
1683 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1684
1685 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001686 return true;
1687}
1688
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001689bool OatWriter::WriteClassOffsets(OutputStream* out) {
1690 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1691 if (oat_dex_file.class_offsets_offset_ != 0u) {
1692 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1693 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1694 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1695 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1696 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001697 return false;
1698 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001699 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1700 return false;
1701 }
1702 }
1703 }
1704 return true;
1705}
1706
1707bool OatWriter::WriteClasses(OutputStream* out) {
1708 for (OatClass& oat_class : oat_classes_) {
1709 if (!oat_class.Write(this, out, oat_data_offset_)) {
1710 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1711 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001712 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001713 }
1714 return true;
1715}
1716
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001717size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001718 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001719 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1720 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1721 return 0;
1722 }
1723 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001724 size_vmap_table_ = relative_offset - vmap_tables_offset;
1725
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001726 return relative_offset;
1727}
1728
1729size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001730 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001731 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001732
Ian Rogers848871b2013-08-05 10:56:33 -07001733 #define DO_TRAMPOLINE(field) \
1734 do { \
1735 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1736 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001737 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001738 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001739 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001740 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001741 return false; \
1742 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001743 size_ ## field += (field)->size(); \
1744 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001745 DCHECK_OFFSET(); \
1746 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001747
Ian Rogers848871b2013-08-05 10:56:33 -07001748 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001749 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001750 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001751 DO_TRAMPOLINE(quick_resolution_trampoline_);
1752 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1753 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001754 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001755 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001756}
1757
Ian Rogers3d504072014-03-01 09:16:49 -08001758size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001759 const size_t file_offset,
1760 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001761 #define VISIT(VisitorType) \
1762 do { \
1763 VisitorType visitor(this, out, file_offset, relative_offset); \
1764 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1765 return 0; \
1766 } \
1767 relative_offset = visitor.GetOffset(); \
1768 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001769
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001770 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001771
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001772 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001773
Vladimir Markob163bb72015-03-31 21:49:49 +01001774 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1775 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1776 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1777
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001778 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001779}
1780
Vladimir Marko944da602016-02-19 12:27:55 +00001781bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001782 // Get the elf file offset of the oat file.
1783 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1784 if (raw_file_offset == static_cast<off_t>(-1)) {
1785 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1786 return false;
1787 }
1788 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1789 return true;
1790}
1791
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001792bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1793 // Read the dex file header and perform minimal verification.
1794 uint8_t raw_header[sizeof(DexFile::Header)];
1795 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1796 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1797 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1798 return false;
1799 }
1800 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1801 return false;
1802 }
1803
1804 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1805 oat_dex_file->dex_file_size_ = header->file_size_;
1806 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1807 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1808 return true;
1809}
1810
1811bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1812 if (!DexFile::IsMagicValid(raw_header)) {
1813 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1814 return false;
1815 }
1816 if (!DexFile::IsVersionValid(raw_header)) {
1817 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1818 return false;
1819 }
1820 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1821 if (header->file_size_ < sizeof(DexFile::Header)) {
1822 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1823 << " File: " << location;
1824 return false;
1825 }
1826 return true;
1827}
1828
1829bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1830 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1831
1832 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001833 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001834 return false;
1835 }
1836
1837 // Write dex files.
1838 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1839 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1840 return false;
1841 }
1842 }
1843
1844 // Close sources.
1845 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1846 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1847 }
1848 zipped_dex_files_.clear();
1849 zip_archives_.clear();
1850 raw_dex_files_.clear();
1851 return true;
1852}
1853
1854bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1855 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1856 return false;
1857 }
1858 if (oat_dex_file->source_.IsZipEntry()) {
1859 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1860 return false;
1861 }
1862 } else if (oat_dex_file->source_.IsRawFile()) {
1863 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1864 return false;
1865 }
1866 } else {
1867 DCHECK(oat_dex_file->source_.IsRawData());
1868 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1869 return false;
1870 }
1871 }
1872
1873 // Update current size and account for the written data.
1874 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1875 size_ += oat_dex_file->dex_file_size_;
1876 size_dex_file_ += oat_dex_file->dex_file_size_;
1877 return true;
1878}
1879
1880bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1881 // Dex files are required to be 4 byte aligned.
1882 size_t original_offset = size_;
1883 size_t offset = RoundUp(original_offset, 4);
1884 size_dex_file_alignment_ += offset - original_offset;
1885
1886 // Seek to the start of the dex file and flush any pending operations in the stream.
1887 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1888 uint32_t start_offset = oat_data_offset_ + offset;
1889 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1890 if (actual_offset != static_cast<off_t>(start_offset)) {
1891 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1892 << " Expected: " << start_offset
1893 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1894 return false;
1895 }
1896 if (!out->Flush()) {
1897 PLOG(ERROR) << "Failed to flush before writing dex file."
1898 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1899 return false;
1900 }
1901 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1902 if (actual_offset != static_cast<off_t>(start_offset)) {
1903 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1904 << " Expected: " << start_offset
1905 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1906 return false;
1907 }
1908
1909 size_ = offset;
1910 oat_dex_file->dex_file_offset_ = offset;
1911 return true;
1912}
1913
1914bool OatWriter::WriteDexFile(OutputStream* rodata,
1915 File* file,
1916 OatDexFile* oat_dex_file,
1917 ZipEntry* dex_file) {
1918 size_t start_offset = oat_data_offset_ + size_;
1919 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1920
1921 // Extract the dex file and get the extracted size.
1922 std::string error_msg;
1923 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1924 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1925 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1926 return false;
1927 }
1928 if (file->Flush() != 0) {
1929 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1930 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1931 return false;
1932 }
1933 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1934 if (extracted_end == static_cast<off_t>(-1)) {
1935 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1936 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1937 return false;
1938 }
1939 if (extracted_end < static_cast<off_t>(start_offset)) {
1940 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1941 << " Start: " << start_offset
1942 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1943 return false;
1944 }
1945 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1946 if (extracted_size < sizeof(DexFile::Header)) {
1947 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1948 << extracted_size << " File: " << oat_dex_file->GetLocation();
1949 return false;
1950 }
1951
1952 // Read the dex file header and extract required data to OatDexFile.
1953 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1954 if (actual_offset != static_cast<off_t>(start_offset)) {
1955 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1956 << " Expected: " << start_offset
1957 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1958 return false;
1959 }
1960 if (!ReadDexFileHeader(file, oat_dex_file)) {
1961 return false;
1962 }
1963 if (extracted_size < oat_dex_file->dex_file_size_) {
1964 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1965 << " file size from header: " << oat_dex_file->dex_file_size_
1966 << " File: " << oat_dex_file->GetLocation();
1967 return false;
1968 }
1969
1970 // Override the checksum from header with the CRC from ZIP entry.
1971 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1972
1973 // Seek both file and stream to the end offset.
1974 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1975 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1976 if (actual_offset != static_cast<off_t>(end_offset)) {
1977 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1978 << " Expected: " << end_offset
1979 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1980 return false;
1981 }
1982 actual_offset = rodata->Seek(end_offset, kSeekSet);
1983 if (actual_offset != static_cast<off_t>(end_offset)) {
1984 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1985 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1986 return false;
1987 }
1988 if (!rodata->Flush()) {
1989 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1990 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1991 return false;
1992 }
1993
1994 // If we extracted more than the size specified in the header, truncate the file.
1995 if (extracted_size > oat_dex_file->dex_file_size_) {
1996 if (file->SetLength(end_offset) != 0) {
1997 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1998 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1999 return false;
2000 }
2001 }
2002
2003 return true;
2004}
2005
2006bool OatWriter::WriteDexFile(OutputStream* rodata,
2007 File* file,
2008 OatDexFile* oat_dex_file,
2009 File* dex_file) {
2010 size_t start_offset = oat_data_offset_ + size_;
2011 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2012
2013 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2014 if (input_offset != static_cast<off_t>(0)) {
2015 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2016 << " Expected: 0"
2017 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2018 return false;
2019 }
2020 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2021 return false;
2022 }
2023
2024 // Copy the input dex file using sendfile().
2025 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2026 PLOG(ERROR) << "Failed to copy dex file to oat file."
2027 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2028 return false;
2029 }
2030 if (file->Flush() != 0) {
2031 PLOG(ERROR) << "Failed to flush dex file."
2032 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2033 return false;
2034 }
2035
2036 // Check file position and seek the stream to the end offset.
2037 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2038 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2039 if (actual_offset != static_cast<off_t>(end_offset)) {
2040 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2041 << " Expected: " << end_offset
2042 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2043 return false;
2044 }
2045 actual_offset = rodata->Seek(end_offset, kSeekSet);
2046 if (actual_offset != static_cast<off_t>(end_offset)) {
2047 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2048 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2049 return false;
2050 }
2051 if (!rodata->Flush()) {
2052 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2053 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2054 return false;
2055 }
2056
2057 return true;
2058}
2059
2060bool OatWriter::WriteDexFile(OutputStream* rodata,
2061 OatDexFile* oat_dex_file,
2062 const uint8_t* dex_file) {
2063 // Note: The raw data has already been checked to contain the header
2064 // and all the data that the header specifies as the file size.
2065 DCHECK(dex_file != nullptr);
2066 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2067 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2068
Vladimir Markoe079e212016-05-25 12:49:49 +01002069 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002070 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2071 << " to " << rodata->GetLocation();
2072 return false;
2073 }
2074 if (!rodata->Flush()) {
2075 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2076 << " File: " << oat_dex_file->GetLocation();
2077 return false;
2078 }
2079
2080 // Update dex file size and resize class offsets in the OatDexFile.
2081 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2082 oat_dex_file->dex_file_size_ = header->file_size_;
2083 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2084 return true;
2085}
2086
2087bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2088 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2089
2090 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2091 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2092 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2093 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2094 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2095 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2096 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2097 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2098 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2099 return false;
2100 }
2101
2102 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2103 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2104
2105 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2106 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2107
2108 // Write OatDexFile.
2109 if (!oat_dex_file->Write(this, rodata)) {
2110 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2111 return false;
2112 }
2113 }
2114
2115 return true;
2116}
2117
2118bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2119 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2120
2121 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2122 if (file->SetLength(new_length) != 0) {
2123 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2124 << "File: " << file->GetPath();
2125 return false;
2126 }
2127 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2128 if (actual_offset != static_cast<off_t>(new_length)) {
2129 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2130 << " Actual: " << actual_offset << " Expected: " << new_length
2131 << " File: " << rodata->GetLocation();
2132 return false;
2133 }
2134 if (!rodata->Flush()) {
2135 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2136 << " File: " << rodata->GetLocation();
2137 return false;
2138 }
2139 return true;
2140}
2141
2142bool OatWriter::OpenDexFiles(
2143 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002144 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002145 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2146 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2147 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2148
2149 if (oat_dex_files_.empty()) {
2150 // Nothing to do.
2151 return true;
2152 }
2153
2154 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2155 size_t length = size_ - map_offset;
2156 std::string error_msg;
2157 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2158 PROT_READ | PROT_WRITE,
2159 MAP_SHARED,
2160 file->Fd(),
2161 oat_data_offset_ + map_offset,
2162 /* low_4gb */ false,
2163 file->GetPath().c_str(),
2164 &error_msg));
2165 if (dex_files_map == nullptr) {
2166 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2167 << " error: " << error_msg;
2168 return false;
2169 }
2170 std::vector<std::unique_ptr<const DexFile>> dex_files;
2171 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2172 // Make sure no one messed with input files while we were copying data.
2173 // At the very least we need consistent file size and number of class definitions.
2174 const uint8_t* raw_dex_file =
2175 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2176 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2177 // Note: ValidateDexFileHeader() already logged an error message.
2178 LOG(ERROR) << "Failed to verify written dex file header!"
2179 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2180 << " ~ " << static_cast<const void*>(raw_dex_file);
2181 return false;
2182 }
2183 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2184 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2185 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2186 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2187 << " Output: " << file->GetPath();
2188 return false;
2189 }
2190 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2191 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2192 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2193 << " Output: " << file->GetPath();
2194 return false;
2195 }
2196
2197 // Now, open the dex file.
2198 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2199 oat_dex_file.dex_file_size_,
2200 oat_dex_file.GetLocation(),
2201 oat_dex_file.dex_file_location_checksum_,
2202 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002203 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002204 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002205 &error_msg));
2206 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002207 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2208 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002209 return false;
2210 }
2211 }
2212
2213 *opened_dex_files_map = std::move(dex_files_map);
2214 *opened_dex_files = std::move(dex_files);
2215 return true;
2216}
2217
2218bool OatWriter::WriteTypeLookupTables(
2219 MemMap* opened_dex_files_map,
2220 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2221 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2222
2223 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2224 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2225 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2226 if (oat_dex_file->lookup_table_offset_ != 0u) {
2227 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2228 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2229 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2230 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2231 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2232 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2233 }
2234 }
2235
2236 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2237 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2238 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2239 return false;
2240 }
2241
2242 return true;
2243}
2244
Vladimir Markof4da6752014-08-01 19:04:18 +01002245bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2246 static const uint8_t kPadding[] = {
2247 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2248 };
2249 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002250 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002251 return false;
2252 }
2253 size_code_alignment_ += aligned_code_delta;
2254 return true;
2255}
2256
Vladimir Marko944da602016-02-19 12:27:55 +00002257void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2258 DCHECK(dex_files_ != nullptr);
2259 DCHECK(relative_patcher_ != nullptr);
2260 DCHECK_NE(oat_data_offset_, 0u);
2261 if (image_writer_ != nullptr && !dex_files_->empty()) {
2262 // The oat data begin may not be initialized yet but the oat file offset is ready.
2263 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2264 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2265 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002266 }
2267}
2268
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002269OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2270 DexFileSource source,
2271 CreateTypeLookupTable create_type_lookup_table)
2272 : source_(source),
2273 create_type_lookup_table_(create_type_lookup_table),
2274 dex_file_size_(0),
2275 offset_(0),
2276 dex_file_location_size_(strlen(dex_file_location)),
2277 dex_file_location_data_(dex_file_location),
2278 dex_file_location_checksum_(0u),
2279 dex_file_offset_(0u),
2280 class_offsets_offset_(0u),
2281 lookup_table_offset_(0u),
2282 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002283}
2284
2285size_t OatWriter::OatDexFile::SizeOf() const {
2286 return sizeof(dex_file_location_size_)
2287 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002288 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002289 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002290 + sizeof(class_offsets_offset_)
2291 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002292}
2293
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002294void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2295 DCHECK_EQ(lookup_table_offset_, 0u);
2296 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2297 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2298 if (table_size != 0u) {
2299 // Type tables are required to be 4 byte aligned.
2300 size_t original_offset = oat_writer->size_;
2301 size_t offset = RoundUp(original_offset, 4);
2302 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2303 lookup_table_offset_ = offset;
2304 oat_writer->size_ = offset + table_size;
2305 oat_writer->size_oat_lookup_table_ += table_size;
2306 }
2307 }
2308}
2309
2310void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2311 DCHECK_EQ(class_offsets_offset_, 0u);
2312 if (!class_offsets_.empty()) {
2313 // Class offsets are required to be 4 byte aligned.
2314 size_t original_offset = oat_writer->size_;
2315 size_t offset = RoundUp(original_offset, 4);
2316 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2317 class_offsets_offset_ = offset;
2318 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2319 }
2320}
2321
2322bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2323 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002324 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002325
Vladimir Markoe079e212016-05-25 12:49:49 +01002326 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002327 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002328 return false;
2329 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002330 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002331
Vladimir Markoe079e212016-05-25 12:49:49 +01002332 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002333 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002334 return false;
2335 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002336 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002337
Vladimir Markoe079e212016-05-25 12:49:49 +01002338 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002339 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002340 return false;
2341 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002342 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002343
Vladimir Markoe079e212016-05-25 12:49:49 +01002344 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002345 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002346 return false;
2347 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002348 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002349
Vladimir Markoe079e212016-05-25 12:49:49 +01002350 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002351 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2352 return false;
2353 }
2354 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2355
Vladimir Markoe079e212016-05-25 12:49:49 +01002356 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002357 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2358 return false;
2359 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002360 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002361
2362 return true;
2363}
2364
2365bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002366 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2368 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002369 return false;
2370 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002371 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002372 return true;
2373}
2374
Brian Carlstromba150c32013-08-27 17:31:03 -07002375OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002376 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002377 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002378 mirror::Class::Status status)
2379 : compiled_methods_(compiled_methods) {
2380 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002381 CHECK_LE(num_non_null_compiled_methods, num_methods);
2382
Brian Carlstrom265091e2013-01-30 14:08:26 -08002383 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002384 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2385
2386 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2387 // apply when there are 0 methods, we just arbitrarily say that 0
2388 // methods means kOatClassNoneCompiled and that we won't use
2389 // kOatClassAllCompiled unless there is at least one compiled
2390 // method. This means in an interpretter only system, we can assert
2391 // that all classes are kOatClassNoneCompiled.
2392 if (num_non_null_compiled_methods == 0) {
2393 type_ = kOatClassNoneCompiled;
2394 } else if (num_non_null_compiled_methods == num_methods) {
2395 type_ = kOatClassAllCompiled;
2396 } else {
2397 type_ = kOatClassSomeCompiled;
2398 }
2399
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002400 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002401 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002402 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002403
2404 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2405 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002406 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002407 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2408 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2409 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2410 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002411 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002412 method_bitmap_size_ = 0;
2413 }
2414
2415 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002416 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002417 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002418 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2419 } else {
2420 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2421 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2422 if (type_ == kOatClassSomeCompiled) {
2423 method_bitmap_->SetBit(i);
2424 }
2425 }
2426 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002427}
2428
Brian Carlstrom265091e2013-01-30 14:08:26 -08002429size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2430 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002431 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2432 if (method_offset == 0) {
2433 return 0;
2434 }
2435 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002436}
2437
2438size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2439 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002440 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002441}
2442
2443size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002444 return sizeof(status_)
2445 + sizeof(type_)
2446 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2447 + method_bitmap_size_
2448 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002449}
2450
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002451bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002452 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002453 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002454 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002455 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002456 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002457 return false;
2458 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002459 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002460
Vladimir Markoe079e212016-05-25 12:49:49 +01002461 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002462 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002463 return false;
2464 }
2465 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002466
Brian Carlstromba150c32013-08-27 17:31:03 -07002467 if (method_bitmap_size_ != 0) {
2468 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002469 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002470 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002471 return false;
2472 }
2473 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002474
Vladimir Markoe079e212016-05-25 12:49:49 +01002475 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002476 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002477 return false;
2478 }
2479 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2480 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002481
Vladimir Markoe079e212016-05-25 12:49:49 +01002482 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002483 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002484 return false;
2485 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002486 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002487 return true;
2488}
2489
Brian Carlstrome24fa612011-09-29 00:53:55 -07002490} // namespace art