blob: d629c0c8877f4c63705f3d7f247d1387570222c5 [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"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000027#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070030#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070031#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000032#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000033#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "dex_file-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000036#include "driver/compiler_driver.h"
37#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010038#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030040#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010041#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010042#include "linker/buffered_output_stream.h"
43#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000044#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000045#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/array.h"
47#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010048#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070049#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010050#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070051#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070052#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070053#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030054#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010055#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010056#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070057#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000058#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070059
60namespace art {
61
Vladimir Marko9bdf1082016-01-21 12:15:52 +000062namespace { // anonymous namespace
63
64typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
65
66const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
67 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
68}
69
Vladimir Markoe079e212016-05-25 12:49:49 +010070class ChecksumUpdatingOutputStream : public OutputStream {
71 public:
72 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
73 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
74
75 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
76 oat_header_->UpdateChecksum(buffer, byte_count);
77 return out_->WriteFully(buffer, byte_count);
78 }
79
80 off_t Seek(off_t offset, Whence whence) OVERRIDE {
81 return out_->Seek(offset, whence);
82 }
83
84 bool Flush() OVERRIDE {
85 return out_->Flush();
86 }
87
88 private:
89 OutputStream* const out_;
90 OatHeader* const oat_header_;
91};
92
Vladimir Marko0c737df2016-08-01 16:33:16 +010093inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
94 // We want to align the code rather than the preheader.
95 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
96 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
97 return aligned_code_offset - unaligned_code_offset;
98}
99
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000100} // anonymous namespace
101
102// Defines the location of the raw dex file to write.
103class OatWriter::DexFileSource {
104 public:
105 explicit DexFileSource(ZipEntry* zip_entry)
106 : type_(kZipEntry), source_(zip_entry) {
107 DCHECK(source_ != nullptr);
108 }
109
110 explicit DexFileSource(File* raw_file)
111 : type_(kRawFile), source_(raw_file) {
112 DCHECK(source_ != nullptr);
113 }
114
115 explicit DexFileSource(const uint8_t* dex_file)
116 : type_(kRawData), source_(dex_file) {
117 DCHECK(source_ != nullptr);
118 }
119
120 bool IsZipEntry() const { return type_ == kZipEntry; }
121 bool IsRawFile() const { return type_ == kRawFile; }
122 bool IsRawData() const { return type_ == kRawData; }
123
124 ZipEntry* GetZipEntry() const {
125 DCHECK(IsZipEntry());
126 DCHECK(source_ != nullptr);
127 return static_cast<ZipEntry*>(const_cast<void*>(source_));
128 }
129
130 File* GetRawFile() const {
131 DCHECK(IsRawFile());
132 DCHECK(source_ != nullptr);
133 return static_cast<File*>(const_cast<void*>(source_));
134 }
135
136 const uint8_t* GetRawData() const {
137 DCHECK(IsRawData());
138 DCHECK(source_ != nullptr);
139 return static_cast<const uint8_t*>(source_);
140 }
141
142 void Clear() {
143 type_ = kNone;
144 source_ = nullptr;
145 }
146
147 private:
148 enum Type {
149 kNone,
150 kZipEntry,
151 kRawFile,
152 kRawData,
153 };
154
155 Type type_;
156 const void* source_;
157};
158
Vladimir Marko49b0f452015-12-10 13:49:19 +0000159class OatWriter::OatClass {
160 public:
161 OatClass(size_t offset,
162 const dchecked_vector<CompiledMethod*>& compiled_methods,
163 uint32_t num_non_null_compiled_methods,
164 mirror::Class::Status status);
165 OatClass(OatClass&& src) = default;
166 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
167 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
168 size_t SizeOf() const;
169 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
170
171 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
172 return compiled_methods_[class_def_method_index];
173 }
174
175 // Offset of start of OatClass from beginning of OatHeader. It is
176 // used to validate file position when writing.
177 size_t offset_;
178
179 // CompiledMethods for each class_def_method_index, or null if no method is available.
180 dchecked_vector<CompiledMethod*> compiled_methods_;
181
182 // Offset from OatClass::offset_ to the OatMethodOffsets for the
183 // class_def_method_index. If 0, it means the corresponding
184 // CompiledMethod entry in OatClass::compiled_methods_ should be
185 // null and that the OatClass::type_ should be kOatClassBitmap.
186 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
187
188 // Data to write.
189
190 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
191 int16_t status_;
192
193 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
194 uint16_t type_;
195
196 uint32_t method_bitmap_size_;
197
198 // bit vector indexed by ClassDef method index. When
199 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
200 // method has an OatMethodOffsets in methods_offsets_, otherwise
201 // the entry was ommited to save space. If OatClassType::type_ is
202 // not is kOatClassBitmap, the bitmap will be null.
203 std::unique_ptr<BitVector> method_bitmap_;
204
205 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
206 // present in the OatClass. Note that some may be missing if
207 // OatClass::compiled_methods_ contains null values (and
208 // oat_method_offsets_offsets_from_oat_class_ should contain 0
209 // values in this case).
210 dchecked_vector<OatMethodOffsets> method_offsets_;
211 dchecked_vector<OatQuickMethodHeader> method_headers_;
212
213 private:
214 size_t GetMethodOffsetsRawSize() const {
215 return method_offsets_.size() * sizeof(method_offsets_[0]);
216 }
217
218 DISALLOW_COPY_AND_ASSIGN(OatClass);
219};
220
221class OatWriter::OatDexFile {
222 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000223 OatDexFile(const char* dex_file_location,
224 DexFileSource source,
225 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000226 OatDexFile(OatDexFile&& src) = default;
227
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000228 const char* GetLocation() const {
229 return dex_file_location_data_;
230 }
231
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000232 void ReserveClassOffsets(OatWriter* oat_writer);
233
Vladimir Marko49b0f452015-12-10 13:49:19 +0000234 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000235 bool Write(OatWriter* oat_writer, OutputStream* out) const;
236 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
237
238 // The source of the dex file.
239 DexFileSource source_;
240
241 // Whether to create the type lookup table.
242 CreateTypeLookupTable create_type_lookup_table_;
243
244 // Dex file size. Initialized when writing the dex file.
245 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000246
247 // Offset of start of OatDexFile from beginning of OatHeader. It is
248 // used to validate file position when writing.
249 size_t offset_;
250
251 // Data to write.
252 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000253 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000254 uint32_t dex_file_location_checksum_;
255 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000256 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000257 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000258
259 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000260 dchecked_vector<uint32_t> class_offsets_;
261
David Sehr9aa352e2016-09-15 18:13:52 -0700262 void InitTypeLookupTable(const DexFile& dex_file, uint8_t* storage) const {
263 lookup_table_.reset(TypeLookupTable::Create(dex_file, storage));
264 }
265
266 TypeLookupTable* GetTypeLookupTable() const {
267 return lookup_table_.get();
268 }
269
Vladimir Marko49b0f452015-12-10 13:49:19 +0000270 private:
David Sehr9aa352e2016-09-15 18:13:52 -0700271 mutable std::unique_ptr<TypeLookupTable> lookup_table_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000272 size_t GetClassOffsetsRawSize() const {
273 return class_offsets_.size() * sizeof(class_offsets_[0]);
274 }
275
276 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
277};
278
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100279#define DCHECK_OFFSET() \
280 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
281 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
282
283#define DCHECK_OFFSET_() \
284 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
285 << "file_offset=" << file_offset << " offset_=" << offset_
286
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000287OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
288 : write_state_(WriteState::kAddingDexFileSources),
289 timings_(timings),
290 raw_dex_files_(),
291 zip_archives_(),
292 zipped_dex_files_(),
293 zipped_dex_file_locations_(),
294 compiler_driver_(nullptr),
295 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800296 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000297 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100298 vdex_size_(0u),
299 vdex_dex_files_offset_(0u),
300 oat_size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000301 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100302 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700303 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100304 size_vdex_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700305 size_dex_file_alignment_(0),
306 size_executable_offset_alignment_(0),
307 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700308 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700310 size_interpreter_to_interpreter_bridge_(0),
311 size_interpreter_to_compiled_code_bridge_(0),
312 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800313 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700314 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700315 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700316 size_quick_to_interpreter_bridge_(0),
317 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100318 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700319 size_code_(0),
320 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100321 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100322 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700323 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700324 size_oat_dex_file_location_size_(0),
325 size_oat_dex_file_location_data_(0),
326 size_oat_dex_file_location_checksum_(0),
327 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000328 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000329 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000330 size_oat_lookup_table_alignment_(0),
331 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000332 size_oat_class_offsets_alignment_(0),
333 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700334 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700335 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700336 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100337 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000338 relative_patcher_(nullptr),
339 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000340}
341
342bool OatWriter::AddDexFileSource(const char* filename,
343 const char* location,
344 CreateTypeLookupTable create_type_lookup_table) {
345 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
346 uint32_t magic;
347 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700348 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
349 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000350 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
351 return false;
352 } else if (IsDexMagic(magic)) {
353 // The file is open for reading, not writing, so it's OK to let the File destructor
354 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700355 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000356 oat_dex_files_.emplace_back(location,
357 DexFileSource(raw_dex_files_.back().get()),
358 create_type_lookup_table);
359 } else if (IsZipMagic(magic)) {
360 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
361 return false;
362 }
363 } else {
364 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
365 return false;
366 }
367 return true;
368}
369
370// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700371bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000372 const char* location,
373 CreateTypeLookupTable create_type_lookup_table) {
374 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
375 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700376 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000377 ZipArchive* zip_archive = zip_archives_.back().get();
378 if (zip_archive == nullptr) {
379 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
380 << error_msg;
381 return false;
382 }
383 for (size_t i = 0; ; ++i) {
384 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
385 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
386 if (entry == nullptr) {
387 break;
388 }
389 zipped_dex_files_.push_back(std::move(entry));
390 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
391 const char* full_location = zipped_dex_file_locations_.back().c_str();
392 oat_dex_files_.emplace_back(full_location,
393 DexFileSource(zipped_dex_files_.back().get()),
394 create_type_lookup_table);
395 }
396 if (zipped_dex_file_locations_.empty()) {
397 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
398 return false;
399 }
400 return true;
401}
402
403// Add dex file source from raw memory.
404bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
405 const char* location,
406 uint32_t location_checksum,
407 CreateTypeLookupTable create_type_lookup_table) {
408 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
409 if (data.size() < sizeof(DexFile::Header)) {
410 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
411 << data.size() << " File: " << location;
412 return false;
413 }
414 if (!ValidateDexFileHeader(data.data(), location)) {
415 return false;
416 }
417 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
418 if (data.size() < header->file_size_) {
419 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
420 << " file size from header: " << header->file_size_ << " File: " << location;
421 return false;
422 }
423
424 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
425 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
426 return true;
427}
428
429dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
430 dchecked_vector<const char*> locations;
431 locations.reserve(oat_dex_files_.size());
432 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
433 locations.push_back(oat_dex_file.GetLocation());
434 }
435 return locations;
436}
437
438bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100439 File* vdex_file,
440 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000441 InstructionSet instruction_set,
442 const InstructionSetFeatures* instruction_set_features,
443 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800444 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000445 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
446 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
447 CHECK(write_state_ == WriteState::kAddingDexFileSources);
448
David Brazdil7b49e6c2016-09-01 11:06:18 +0100449 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
450 if (!RecordOatDataOffset(oat_rodata)) {
451 return false;
452 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000453
454 std::unique_ptr<MemMap> dex_files_map;
455 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100456
457 // Initialize VDEX and OAT headers.
458 if (kIsVdexEnabled) {
459 size_vdex_header_ = sizeof(VdexFile::Header);
460 vdex_size_ = size_vdex_header_;
461 }
462 size_t oat_data_offset = InitOatHeader(instruction_set,
463 instruction_set_features,
464 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
465 key_value_store);
466 oat_size_ = InitOatDexFiles(oat_data_offset);
467
468 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
469
470 if (kIsVdexEnabled) {
471 std::unique_ptr<BufferedOutputStream> vdex_out(
472 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
473
474 // Write DEX files into VDEX, mmap and open them.
475 if (!WriteDexFiles(vdex_out.get(), vdex_file) ||
476 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
477 return false;
478 }
479
480 // VDEX is finalized. Seek to the beginning of the file and write the header.
481 if (!WriteVdexHeader(vdex_out.get())) {
482 return false;
483 }
484 } else {
485 // Write DEX files into OAT, mmap and open them.
486 if (!WriteDexFiles(oat_rodata, vdex_file) ||
487 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
488 return false;
489 }
490
491 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
492 // difficult because we're not using the OutputStream directly.
493 if (!oat_dex_files_.empty()) {
494 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
495 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
496 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000498
David Brazdil7b49e6c2016-09-01 11:06:18 +0100499 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000500 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
501 return false;
502 }
503
David Brazdil7b49e6c2016-09-01 11:06:18 +0100504 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000505 for (OatDexFile& oat_dex_file : oat_dex_files_) {
506 oat_dex_file.ReserveClassOffsets(this);
507 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100508
David Brazdil7b49e6c2016-09-01 11:06:18 +0100509 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000510 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
511 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000512 }
513
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000514 *opened_dex_files_map = std::move(dex_files_map);
515 *opened_dex_files = std::move(dex_files);
516 write_state_ = WriteState::kPrepareLayout;
517 return true;
518}
519
520void OatWriter::PrepareLayout(const CompilerDriver* compiler,
521 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000522 const std::vector<const DexFile*>& dex_files,
523 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 CHECK(write_state_ == WriteState::kPrepareLayout);
525
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000526 compiler_driver_ = compiler;
527 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000528 dex_files_ = &dex_files;
529 relative_patcher_ = relative_patcher;
530 SetMultiOatRelativePatcherAdjustment();
531
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000532 if (compiling_boot_image_) {
533 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800534 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100535 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000536 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100537
David Brazdil7b49e6c2016-09-01 11:06:18 +0100538 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800539 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000540 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800541 offset = InitOatClasses(offset);
542 }
543 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000544 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100545 offset = InitOatMaps(offset);
546 }
547 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000548 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800549 offset = InitOatCode(offset);
550 }
551 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000552 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800553 offset = InitOatCodeDexFiles(offset);
554 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100555 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700556
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800557 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100558 // Allocate space for app dex cache arrays in the .bss section.
David Brazdil7b49e6c2016-09-01 11:06:18 +0100559 size_t bss_start = RoundUp(oat_size_, kPageSize);
Andreas Gampe542451c2016-07-26 09:02:02 -0700560 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100561 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000562 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100563 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
564 DexCacheArraysLayout layout(pointer_size, dex_file);
565 bss_size_ += layout.Size();
566 }
567 }
568
Brian Carlstrome24fa612011-09-29 00:53:55 -0700569 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800570 if (compiling_boot_image_) {
571 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000572 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800573 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000574
575 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700576}
577
Ian Rogers0571d352011-11-03 19:51:38 -0700578OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700579}
580
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100581class OatWriter::DexMethodVisitor {
582 public:
583 DexMethodVisitor(OatWriter* writer, size_t offset)
584 : writer_(writer),
585 offset_(offset),
586 dex_file_(nullptr),
587 class_def_index_(DexFile::kDexNoIndex) {
588 }
589
590 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
591 DCHECK(dex_file_ == nullptr);
592 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
593 dex_file_ = dex_file;
594 class_def_index_ = class_def_index;
595 return true;
596 }
597
598 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
599
600 virtual bool EndClass() {
601 if (kIsDebugBuild) {
602 dex_file_ = nullptr;
603 class_def_index_ = DexFile::kDexNoIndex;
604 }
605 return true;
606 }
607
608 size_t GetOffset() const {
609 return offset_;
610 }
611
612 protected:
613 virtual ~DexMethodVisitor() { }
614
615 OatWriter* const writer_;
616
617 // The offset is usually advanced for each visited method by the derived class.
618 size_t offset_;
619
620 // The dex file and class def index are set in StartClass().
621 const DexFile* dex_file_;
622 size_t class_def_index_;
623};
624
625class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
626 public:
627 OatDexMethodVisitor(OatWriter* writer, size_t offset)
628 : DexMethodVisitor(writer, offset),
629 oat_class_index_(0u),
630 method_offsets_index_(0u) {
631 }
632
633 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
634 DexMethodVisitor::StartClass(dex_file, class_def_index);
635 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
636 method_offsets_index_ = 0u;
637 return true;
638 }
639
640 bool EndClass() {
641 ++oat_class_index_;
642 return DexMethodVisitor::EndClass();
643 }
644
645 protected:
646 size_t oat_class_index_;
647 size_t method_offsets_index_;
648};
649
650class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
651 public:
652 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
653 : DexMethodVisitor(writer, offset),
654 compiled_methods_(),
655 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000656 size_t num_classes = 0u;
657 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
658 num_classes += oat_dex_file.class_offsets_.size();
659 }
660 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100661 compiled_methods_.reserve(256u);
662 }
663
664 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
665 DexMethodVisitor::StartClass(dex_file, class_def_index);
666 compiled_methods_.clear();
667 num_non_null_compiled_methods_ = 0u;
668 return true;
669 }
670
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300671 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
672 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100673 // Fill in the compiled_methods_ array for methods that have a
674 // CompiledMethod. We track the number of non-null entries in
675 // num_non_null_compiled_methods_ since we only want to allocate
676 // OatMethodOffsets for the compiled methods.
677 uint32_t method_idx = it.GetMemberIndex();
678 CompiledMethod* compiled_method =
679 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
680 compiled_methods_.push_back(compiled_method);
681 if (compiled_method != nullptr) {
682 ++num_non_null_compiled_methods_;
683 }
684 return true;
685 }
686
687 bool EndClass() {
688 ClassReference class_ref(dex_file_, class_def_index_);
689 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
690 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700691 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100692 status = compiled_class->GetStatus();
693 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
694 status = mirror::Class::kStatusError;
695 } else {
696 status = mirror::Class::kStatusNotReady;
697 }
698
Vladimir Marko49b0f452015-12-10 13:49:19 +0000699 writer_->oat_classes_.emplace_back(offset_,
700 compiled_methods_,
701 num_non_null_compiled_methods_,
702 status);
703 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100704 return DexMethodVisitor::EndClass();
705 }
706
707 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000708 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100709 size_t num_non_null_compiled_methods_;
710};
711
712class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
713 public:
714 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100715 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100716 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100717 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100718 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
719 }
720
721 bool EndClass() {
722 OatDexMethodVisitor::EndClass();
723 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100724 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100725 }
726 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100727 }
728
729 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700730 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000731 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100732 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
733
734 if (compiled_method != nullptr) {
735 // Derived from CompiledMethod.
736 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100737
Vladimir Marko35831e82015-09-11 11:59:18 +0100738 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
739 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800740 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800741
David Srbecky009e2a62015-04-15 02:46:30 +0100742 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100743 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800744 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000745 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000746 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
747 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800748 // Duplicate methods, we want the same code for both of them so that the oat writer puts
749 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800750 } else {
751 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100752 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800753 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000754 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100755 quick_code_offset = dedupe_map_.GetOrCreate(
756 compiled_method,
757 [this, &deduped, compiled_method, &it, thumb_offset]() {
758 deduped = false;
759 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
760 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800761 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100763 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000764 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100765 // TODO: Should this be a hard failure?
766 LOG(WARNING) << "Multiple definitions of "
767 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000768 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
769 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100770 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000771 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100772 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800773 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100774
Elliott Hughes956af0f2014-12-11 14:34:28 -0800775 // Update quick method header.
776 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
777 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800778 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100779 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
780 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100781 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800782 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
783 // to 0-offset and we need to adjust it by code_offset.
784 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100785 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800786 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100787 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800788 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800789 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
790 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
791 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100792 *method_header = OatQuickMethodHeader(vmap_table_offset,
793 frame_size_in_bytes,
794 core_spill_mask,
795 fp_spill_mask,
796 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100797
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000798 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800799 // Update offsets. (Checksum is updated when writing.)
800 offset_ += sizeof(*method_header); // Method header is prepended before code.
801 offset_ += code_size;
802 // Record absolute patch locations.
803 if (!compiled_method->GetPatches().empty()) {
804 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
805 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000806 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100807 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100808 }
809 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100810 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 }
Alex Light78382fa2014-06-06 15:45:32 -0700812
David Srbecky91cc06c2016-03-07 16:13:58 +0000813 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000814 // Exclude quickened dex methods (code_size == 0) since they have no native code.
815 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
816 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800817 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000818 debug::MethodDebugInfo info = debug::MethodDebugInfo();
819 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000820 info.dex_file = dex_file_;
821 info.class_def_index = class_def_index_;
822 info.dex_method_index = it.GetMemberIndex();
823 info.access_flags = it.GetMethodAccessFlags();
824 info.code_item = it.GetMethodCodeItem();
825 info.isa = compiled_method->GetInstructionSet();
826 info.deduped = deduped;
827 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
828 info.is_optimized = method_header->IsOptimized();
829 info.is_code_address_text_relative = true;
830 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
831 info.code_size = code_size;
832 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
833 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
834 info.cfi = compiled_method->GetCFIInfo();
835 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100836 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100837
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100838 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
839 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
840 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841 ++method_offsets_index_;
842 }
843
844 return true;
845 }
846
847 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000848 struct CodeOffsetsKeyComparator {
849 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100850 // Code is deduplicated by CompilerDriver, compare only data pointers.
851 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
852 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000853 }
854 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100855 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
856 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000857 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100858 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
859 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000860 }
861 return false;
862 }
863 };
864
David Srbecky009e2a62015-04-15 02:46:30 +0100865 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
866 const ClassDataItemIterator& it,
867 uint32_t thumb_offset) {
868 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100869 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100870 offset_ += CodeAlignmentSize(offset_, *compiled_method);
871 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100872 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
873 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
874 }
875
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100876 // 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 Marko8a630572014-04-09 18:45:35 +0100878 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100879
David Srbecky009e2a62015-04-15 02:46:30 +0100880 // Cache of compiler's --debuggable option.
881 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100882};
883
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100884class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
885 public:
886 InitMapMethodVisitor(OatWriter* writer, size_t offset)
887 : OatDexMethodVisitor(writer, offset) {
888 }
889
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700890 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700891 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000892 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100893 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
894
895 if (compiled_method != nullptr) {
896 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100897 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100898
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100899 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100900 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100901 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100902 size_t offset = dedupe_map_.GetOrCreate(
903 map.data(),
904 [this, map_size]() {
905 uint32_t new_offset = offset_;
906 offset_ += map_size;
907 return new_offset;
908 });
909 // Code offset is not initialized yet, so set the map offset to 0u-offset.
910 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
911 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100912 }
913 ++method_offsets_index_;
914 }
915
916 return true;
917 }
918
919 private:
920 // Deduplication is already done on a pointer basis by the compiler driver,
921 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100922 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923};
924
925class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
926 public:
927 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800928 : OatDexMethodVisitor(writer, offset),
929 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100930 }
931
932 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700933 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800934 const DexFile::TypeId& type_id =
935 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
936 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
937 // Skip methods that are not in the image.
938 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
939 return true;
940 }
941
Vladimir Marko49b0f452015-12-10 13:49:19 +0000942 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100943 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
944
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800945 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946 if (compiled_method != nullptr) {
947 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
948 offsets = oat_class->method_offsets_[method_offsets_index_];
949 ++method_offsets_index_;
950 }
951
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100953 // Unchecked as we hold mutator_lock_ on entry.
954 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800955 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700956 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
957 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800958 ArtMethod* method;
959 if (writer_->HasBootImage()) {
960 const InvokeType invoke_type = it.GetMethodInvokeType(
961 dex_file_->GetClassDef(class_def_index_));
962 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
963 *dex_file_,
964 it.GetMemberIndex(),
965 dex_cache,
966 ScopedNullHandle<mirror::ClassLoader>(),
967 nullptr,
968 invoke_type);
969 if (method == nullptr) {
970 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
971 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
972 soa.Self()->AssertPendingException();
973 mirror::Throwable* exc = soa.Self()->GetException();
974 std::string dump = exc->Dump();
975 LOG(FATAL) << dump;
976 UNREACHABLE();
977 }
978 } else {
979 // Should already have been resolved by the compiler, just peek into the dex cache.
980 // It may not be resolved if the class failed to verify, in this case, don't set the
981 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
982 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700983 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800984 if (method != nullptr &&
985 compiled_method != nullptr &&
986 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100987 method->SetEntryPointFromQuickCompiledCodePtrSize(
988 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
989 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100990
991 return true;
992 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800993
994 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -0700995 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100996};
997
998class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
999 public:
1000 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001001 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001002 : OatDexMethodVisitor(writer, relative_offset),
1003 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001004 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001005 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001006 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001007 class_linker_(Runtime::Current()->GetClassLinker()),
1008 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001009 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001010 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001011 // If we're creating the image, the address space must be ready so that we can apply patches.
1012 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001013 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001014 }
1015
Vladimir Markof4da6752014-08-01 19:04:18 +01001016 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001017 }
1018
1019 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001020 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001021 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1022 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001023 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001024 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001025 }
1026 return true;
1027 }
1028
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001029 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001030 bool result = OatDexMethodVisitor::EndClass();
1031 if (oat_class_index_ == writer_->oat_classes_.size()) {
1032 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001033 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001034 if (UNLIKELY(offset_ == 0u)) {
1035 PLOG(ERROR) << "Failed to write final relative call thunks";
1036 result = false;
1037 }
1038 }
1039 return result;
1040 }
1041
1042 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001043 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001044 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001045 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1046
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001047 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001048 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001049 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001050 size_t file_offset = file_offset_;
1051 OutputStream* out = out_;
1052
Vladimir Marko35831e82015-09-11 11:59:18 +01001053 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1054 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001055
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001056 // Deduplicate code arrays.
1057 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1058 if (method_offsets.code_offset_ > offset_) {
1059 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1060 if (offset_ == 0u) {
1061 ReportWriteFailure("relative call thunk", it);
1062 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001063 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001064 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1065 if (alignment_size != 0) {
1066 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001067 ReportWriteFailure("code alignment padding", it);
1068 return false;
1069 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001070 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001071 DCHECK_OFFSET_();
1072 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001073 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001074 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1075 DCHECK_EQ(method_offsets.code_offset_,
1076 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1077 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1078 const OatQuickMethodHeader& method_header =
1079 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001080 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001081 ReportWriteFailure("method header", it);
1082 return false;
1083 }
1084 writer_->size_method_header_ += sizeof(method_header);
1085 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001086 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001087
1088 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001089 patched_code_.assign(quick_code.begin(), quick_code.end());
1090 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001091 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001092 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001093 switch (patch.GetType()) {
1094 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001095 // NOTE: Relative calls across oat files are not supported.
1096 uint32_t target_offset = GetTargetOffset(patch);
1097 writer_->relative_patcher_->PatchCall(&patched_code_,
1098 literal_offset,
1099 offset_ + literal_offset,
1100 target_offset);
1101 break;
1102 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001103 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001104 uint32_t target_offset = GetDexCacheOffset(patch);
1105 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1106 patch,
1107 offset_ + literal_offset,
1108 target_offset);
1109 break;
1110 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001111 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001112 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1113 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1114 patch,
1115 offset_ + literal_offset,
1116 target_offset);
1117 break;
1118 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001119 case LinkerPatch::Type::kTypeRelative: {
1120 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1121 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1122 patch,
1123 offset_ + literal_offset,
1124 target_offset);
1125 break;
1126 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001127 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001128 uint32_t target_offset = GetTargetOffset(patch);
1129 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1130 break;
1131 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001132 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001133 ArtMethod* method = GetTargetMethod(patch);
1134 PatchMethodAddress(&patched_code_, literal_offset, method);
1135 break;
1136 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001137 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001138 mirror::String* string = GetTargetString(patch);
1139 PatchObjectAddress(&patched_code_, literal_offset, string);
1140 break;
1141 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001142 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001143 mirror::Class* type = GetTargetType(patch);
1144 PatchObjectAddress(&patched_code_, literal_offset, type);
1145 break;
1146 }
1147 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001148 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001149 break;
1150 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001151 }
1152 }
1153 }
1154
Vladimir Markoe079e212016-05-25 12:49:49 +01001155 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001156 ReportWriteFailure("method code", it);
1157 return false;
1158 }
1159 writer_->size_code_ += code_size;
1160 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001161 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001162 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001163 ++method_offsets_index_;
1164 }
1165
1166 return true;
1167 }
1168
1169 private:
1170 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001171 const size_t file_offset_;
1172 const ScopedObjectAccess soa_;
1173 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001174 ClassLinker* const class_linker_;
1175 mirror::DexCache* dex_cache_;
1176 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001177
1178 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1179 PLOG(ERROR) << "Failed to write " << what << " for "
1180 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1181 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001182
Mathieu Chartiere401d142015-04-22 13:56:20 -07001183 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001184 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001185 MethodReference ref = patch.TargetMethod();
1186 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001187 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1188 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 ArtMethod* method = dex_cache->GetResolvedMethod(
1190 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001191 CHECK(method != nullptr);
1192 return method;
1193 }
1194
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001195 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001196 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1197 // If there's no new compiled code, either we're compiling an app and the target method
1198 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001199 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001200 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001201 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001202 PointerSize size =
1203 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001204 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1205 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001206 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001207 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1208 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1209 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1210 target_offset = PointerToLowMemUInt32(oat_code_offset);
1211 } else {
1212 target_offset = target->IsNative()
1213 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1214 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1215 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001216 }
1217 return target_offset;
1218 }
1219
Vladimir Marko052164a2016-04-27 13:54:18 +01001220 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001221 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001222 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001223 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001224 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1225 }
1226
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001227 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001228 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001229 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1230 CHECK(type != nullptr);
1231 return type;
1232 }
1233
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001234 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001235 ScopedObjectAccessUnchecked soa(Thread::Current());
1236 StackHandleScope<1> hs(soa.Self());
1237 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1238 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1239 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1240 patch.TargetStringIndex(),
1241 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001242 DCHECK(string != nullptr);
1243 DCHECK(writer_->HasBootImage() ||
1244 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1245 return string;
1246 }
1247
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001248 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001249 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001250 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1251 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1252 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1253 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001254 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001255 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001256 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1257 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001258 }
1259 }
1260
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001261 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001262 DCHECK(writer_->HasBootImage());
1263 object = writer_->image_writer_->GetImageAddress(object);
1264 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1265 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1266 // TODO: Clean up offset types. The target offset must be treated as signed.
1267 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1268 }
1269
Vladimir Markof4da6752014-08-01 19:04:18 +01001270 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001271 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001272 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001273 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001274 } else {
1275 // NOTE: We're using linker patches for app->boot references when the image can
1276 // be relocated and therefore we need to emit .oat_patches. We're not using this
1277 // for app->app references, so check that the object is in the image space.
1278 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001279 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001280 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001281 uint32_t address = PointerToLowMemUInt32(object);
1282 DCHECK_LE(offset + 4, code->size());
1283 uint8_t* data = &(*code)[offset];
1284 data[0] = address & 0xffu;
1285 data[1] = (address >> 8) & 0xffu;
1286 data[2] = (address >> 16) & 0xffu;
1287 data[3] = (address >> 24) & 0xffu;
1288 }
1289
Mathieu Chartiere401d142015-04-22 13:56:20 -07001290 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001291 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001292 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001293 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001294 } else if (kIsDebugBuild) {
1295 // NOTE: We're using linker patches for app->boot references when the image can
1296 // be relocated and therefore we need to emit .oat_patches. We're not using this
1297 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001298 std::vector<gc::space::ImageSpace*> image_spaces =
1299 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1300 bool contains_method = false;
1301 for (gc::space::ImageSpace* image_space : image_spaces) {
1302 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1303 contains_method |=
1304 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1305 }
1306 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001307 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001308 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001309 uint32_t address = PointerToLowMemUInt32(method);
1310 DCHECK_LE(offset + 4, code->size());
1311 uint8_t* data = &(*code)[offset];
1312 data[0] = address & 0xffu;
1313 data[1] = (address >> 8) & 0xffu;
1314 data[2] = (address >> 16) & 0xffu;
1315 data[3] = (address >> 24) & 0xffu;
1316 }
1317
Vladimir Markof4da6752014-08-01 19:04:18 +01001318 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001319 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001320 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001321 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001322 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1323 // TODO: Clean up offset types.
1324 // The target_offset must be treated as signed for cross-oat patching.
1325 const void* target = reinterpret_cast<const void*>(
1326 writer_->image_writer_->GetOatDataBegin(oat_index) +
1327 static_cast<int32_t>(target_offset));
1328 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001329 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001330 DCHECK_LE(offset + 4, code->size());
1331 uint8_t* data = &(*code)[offset];
1332 data[0] = address & 0xffu;
1333 data[1] = (address >> 8) & 0xffu;
1334 data[2] = (address >> 16) & 0xffu;
1335 data[3] = (address >> 24) & 0xffu;
1336 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001337};
1338
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001339class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1340 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001341 WriteMapMethodVisitor(OatWriter* writer,
1342 OutputStream* out,
1343 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001344 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001345 : OatDexMethodVisitor(writer, relative_offset),
1346 out_(out),
1347 file_offset_(file_offset) {
1348 }
1349
1350 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001351 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001352 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1353
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001354 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001355 size_t file_offset = file_offset_;
1356 OutputStream* out = out_;
1357
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001358 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1359 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001360 ++method_offsets_index_;
1361
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001362 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1363 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1364 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1365 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1366
1367 if (map_offset != 0u) {
1368 // Transform map_offset to actual oat data offset.
1369 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1370 DCHECK_NE(map_offset, 0u);
1371 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1372
1373 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1374 size_t map_size = map.size() * sizeof(map[0]);
1375 if (map_offset == offset_) {
1376 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001377 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001378 ReportWriteFailure(it);
1379 return false;
1380 }
1381 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001382 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001383 }
1384 DCHECK_OFFSET_();
1385 }
1386
1387 return true;
1388 }
1389
1390 private:
1391 OutputStream* const out_;
1392 size_t const file_offset_;
1393
1394 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001395 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001396 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1397 }
1398};
1399
1400// Visit all methods from all classes in all dex files with the specified visitor.
1401bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1402 for (const DexFile* dex_file : *dex_files_) {
1403 const size_t class_def_count = dex_file->NumClassDefs();
1404 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1405 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1406 return false;
1407 }
1408 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001409 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001410 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001411 ClassDataItemIterator it(*dex_file, class_data);
1412 while (it.HasNextStaticField()) {
1413 it.Next();
1414 }
1415 while (it.HasNextInstanceField()) {
1416 it.Next();
1417 }
1418 size_t class_def_method_index = 0u;
1419 while (it.HasNextDirectMethod()) {
1420 if (!visitor->VisitMethod(class_def_method_index, it)) {
1421 return false;
1422 }
1423 ++class_def_method_index;
1424 it.Next();
1425 }
1426 while (it.HasNextVirtualMethod()) {
1427 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1428 return false;
1429 }
1430 ++class_def_method_index;
1431 it.Next();
1432 }
1433 }
1434 if (UNLIKELY(!visitor->EndClass())) {
1435 return false;
1436 }
1437 }
1438 }
1439 return true;
1440}
1441
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001442size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1443 const InstructionSetFeatures* instruction_set_features,
1444 uint32_t num_dex_files,
1445 SafeMap<std::string, std::string>* key_value_store) {
1446 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1447 oat_header_.reset(OatHeader::Create(instruction_set,
1448 instruction_set_features,
1449 num_dex_files,
1450 key_value_store));
1451 size_oat_header_ += sizeof(OatHeader);
1452 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001453 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001454}
1455
1456size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001457 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1458 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001459 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001460 oat_dex_file.offset_ = offset;
1461 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001462 }
1463 return offset;
1464}
1465
Brian Carlstrom389efb02012-01-11 12:06:26 -08001466size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001467 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 InitOatClassesMethodVisitor visitor(this, offset);
1469 bool success = VisitDexMethods(&visitor);
1470 CHECK(success);
1471 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001472
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001473 // Update oat_dex_files_.
1474 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001475 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1476 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001477 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001478 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001479 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001480 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001481 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001482 CHECK(oat_class_it == oat_classes_.end());
1483
1484 return offset;
1485}
1486
1487size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001488 InitMapMethodVisitor visitor(this, offset);
1489 bool success = VisitDexMethods(&visitor);
1490 DCHECK(success);
1491 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001492
Brian Carlstrome24fa612011-09-29 00:53:55 -07001493 return offset;
1494}
1495
1496size_t OatWriter::InitOatCode(size_t offset) {
1497 // calculate the offsets within OatHeader to executable code
1498 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001499 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001500 // required to be on a new page boundary
1501 offset = RoundUp(offset, kPageSize);
1502 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001503 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001504 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001505 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001506
Ian Rogers848871b2013-08-05 10:56:33 -07001507 #define DO_TRAMPOLINE(field, fn_name) \
1508 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001509 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1510 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001511 (field) = compiler_driver_->Create ## fn_name(); \
1512 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001513
Ian Rogers848871b2013-08-05 10:56:33 -07001514 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001515 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001516 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001517 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1518 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001519
Ian Rogers848871b2013-08-05 10:56:33 -07001520 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001521 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001522 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1523 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1524 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001525 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001526 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001527 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001528 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001529 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001530 return offset;
1531}
1532
1533size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001534 #define VISIT(VisitorType) \
1535 do { \
1536 VisitorType visitor(this, offset); \
1537 bool success = VisitDexMethods(&visitor); \
1538 DCHECK(success); \
1539 offset = visitor.GetOffset(); \
1540 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001541
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001542 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001543 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001544 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001545 }
Logan Chien8b977d32012-02-21 19:14:55 +08001546
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001547 #undef VISIT
1548
Brian Carlstrome24fa612011-09-29 00:53:55 -07001549 return offset;
1550}
1551
David Srbeckybc90fd02015-04-22 19:40:27 +01001552bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001553 CHECK(write_state_ == WriteState::kWriteRoData);
1554
Vladimir Markoe079e212016-05-25 12:49:49 +01001555 // Wrap out to update checksum with each write.
1556 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1557 out = &checksum_updating_out;
1558
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001559 if (!WriteClassOffsets(out)) {
1560 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001561 return false;
1562 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001563
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001564 if (!WriteClasses(out)) {
1565 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001566 return false;
1567 }
1568
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001570 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001571 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001572 return false;
1573 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001574 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001575 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001576 relative_offset = WriteMaps(out, file_offset, relative_offset);
1577 if (relative_offset == 0) {
1578 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1579 return false;
1580 }
1581
David Srbeckybc90fd02015-04-22 19:40:27 +01001582 // Write padding.
1583 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1584 relative_offset += size_executable_offset_alignment_;
1585 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1586 size_t expected_file_offset = file_offset + relative_offset;
1587 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1588 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1589 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1590 return 0;
1591 }
1592 DCHECK_OFFSET();
1593
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001594 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001595 return true;
1596}
1597
1598bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001599 CHECK(write_state_ == WriteState::kWriteText);
1600
Vladimir Markoe079e212016-05-25 12:49:49 +01001601 // Wrap out to update checksum with each write.
1602 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1603 out = &checksum_updating_out;
1604
Vladimir Marko944da602016-02-19 12:27:55 +00001605 SetMultiOatRelativePatcherAdjustment();
1606
David Srbeckybc90fd02015-04-22 19:40:27 +01001607 const size_t file_offset = oat_data_offset_;
1608 size_t relative_offset = oat_header_->GetExecutableOffset();
1609 DCHECK_OFFSET();
1610
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001611 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001612 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001613 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001614 return false;
1615 }
1616
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001617 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1618 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001619 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001620 return false;
1621 }
1622
Vladimir Markof4da6752014-08-01 19:04:18 +01001623 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001624 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001625 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1626 return false;
1627 }
1628
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001629 if (kIsDebugBuild) {
1630 uint32_t size_total = 0;
1631 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001632 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1633 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001634
David Brazdil7b49e6c2016-09-01 11:06:18 +01001635 DO_STAT(size_vdex_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001636 DO_STAT(size_dex_file_alignment_);
1637 DO_STAT(size_executable_offset_alignment_);
1638 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001639 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001640 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001641 DO_STAT(size_interpreter_to_interpreter_bridge_);
1642 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1643 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001644 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001645 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001646 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001647 DO_STAT(size_quick_to_interpreter_bridge_);
1648 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001649 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001650 DO_STAT(size_code_);
1651 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001652 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001653 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001654 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001655 DO_STAT(size_oat_dex_file_location_size_);
1656 DO_STAT(size_oat_dex_file_location_data_);
1657 DO_STAT(size_oat_dex_file_location_checksum_);
1658 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001659 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001660 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001661 DO_STAT(size_oat_lookup_table_alignment_);
1662 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001663 DO_STAT(size_oat_class_offsets_alignment_);
1664 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001665 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001666 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001667 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001668 DO_STAT(size_oat_class_method_offsets_);
1669 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001670
David Brazdil7b49e6c2016-09-01 11:06:18 +01001671 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1672
1673 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1674 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001675 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001676
David Brazdil7b49e6c2016-09-01 11:06:18 +01001677 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1678 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001679
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001680 write_state_ = WriteState::kWriteHeader;
1681 return true;
1682}
1683
1684bool OatWriter::WriteHeader(OutputStream* out,
1685 uint32_t image_file_location_oat_checksum,
1686 uintptr_t image_file_location_oat_begin,
1687 int32_t image_patch_delta) {
1688 CHECK(write_state_ == WriteState::kWriteHeader);
1689
1690 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1691 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1692 if (compiler_driver_->IsBootImage()) {
1693 CHECK_EQ(image_patch_delta, 0);
1694 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1695 } else {
1696 CHECK_ALIGNED(image_patch_delta, kPageSize);
1697 oat_header_->SetImagePatchDelta(image_patch_delta);
1698 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001699 oat_header_->UpdateChecksumWithHeaderData();
1700
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001701 const size_t file_offset = oat_data_offset_;
1702
1703 off_t current_offset = out->Seek(0, kSeekCurrent);
1704 if (current_offset == static_cast<off_t>(-1)) {
1705 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1706 return false;
1707 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001708 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001709 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1710 return false;
1711 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001712 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001713
1714 // Flush all other data before writing the header.
1715 if (!out->Flush()) {
1716 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1717 return false;
1718 }
1719 // Write the header.
1720 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001721 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001722 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1723 return false;
1724 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001725 // Flush the header data.
1726 if (!out->Flush()) {
1727 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001728 return false;
1729 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001730
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001731 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1732 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1733 return false;
1734 }
1735 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1736
1737 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001738 return true;
1739}
1740
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001741bool OatWriter::WriteClassOffsets(OutputStream* out) {
1742 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1743 if (oat_dex_file.class_offsets_offset_ != 0u) {
1744 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1745 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1746 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1747 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1748 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001749 return false;
1750 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001751 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1752 return false;
1753 }
1754 }
1755 }
1756 return true;
1757}
1758
1759bool OatWriter::WriteClasses(OutputStream* out) {
1760 for (OatClass& oat_class : oat_classes_) {
1761 if (!oat_class.Write(this, out, oat_data_offset_)) {
1762 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1763 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001764 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001765 }
1766 return true;
1767}
1768
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001769size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001770 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001771 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1772 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1773 return 0;
1774 }
1775 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001776 size_vmap_table_ = relative_offset - vmap_tables_offset;
1777
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001778 return relative_offset;
1779}
1780
1781size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001782 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001783 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001784
Ian Rogers848871b2013-08-05 10:56:33 -07001785 #define DO_TRAMPOLINE(field) \
1786 do { \
1787 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1788 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001789 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001790 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001791 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001792 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001793 return false; \
1794 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001795 size_ ## field += (field)->size(); \
1796 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001797 DCHECK_OFFSET(); \
1798 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001799
Ian Rogers848871b2013-08-05 10:56:33 -07001800 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001801 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001802 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001803 DO_TRAMPOLINE(quick_resolution_trampoline_);
1804 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1805 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001806 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001807 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001808}
1809
Ian Rogers3d504072014-03-01 09:16:49 -08001810size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001811 const size_t file_offset,
1812 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001813 #define VISIT(VisitorType) \
1814 do { \
1815 VisitorType visitor(this, out, file_offset, relative_offset); \
1816 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1817 return 0; \
1818 } \
1819 relative_offset = visitor.GetOffset(); \
1820 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001821
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001822 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001823
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001824 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001825
Vladimir Markob163bb72015-03-31 21:49:49 +01001826 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1827 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1828 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1829
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001830 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001831}
1832
Vladimir Marko944da602016-02-19 12:27:55 +00001833bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001834 // Get the elf file offset of the oat file.
1835 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1836 if (raw_file_offset == static_cast<off_t>(-1)) {
1837 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1838 return false;
1839 }
1840 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1841 return true;
1842}
1843
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001844bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1845 // Read the dex file header and perform minimal verification.
1846 uint8_t raw_header[sizeof(DexFile::Header)];
1847 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1848 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1849 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1850 return false;
1851 }
1852 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1853 return false;
1854 }
1855
1856 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1857 oat_dex_file->dex_file_size_ = header->file_size_;
1858 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1859 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1860 return true;
1861}
1862
1863bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1864 if (!DexFile::IsMagicValid(raw_header)) {
1865 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1866 return false;
1867 }
1868 if (!DexFile::IsVersionValid(raw_header)) {
1869 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1870 return false;
1871 }
1872 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1873 if (header->file_size_ < sizeof(DexFile::Header)) {
1874 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1875 << " File: " << location;
1876 return false;
1877 }
1878 return true;
1879}
1880
David Brazdil7b49e6c2016-09-01 11:06:18 +01001881bool OatWriter::WriteDexFiles(OutputStream* out, File* file) {
1882 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001883
David Brazdil7b49e6c2016-09-01 11:06:18 +01001884 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001885
1886 // Write dex files.
1887 for (OatDexFile& oat_dex_file : oat_dex_files_) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001888 if (!WriteDexFile(out, file, &oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001889 return false;
1890 }
1891 }
1892
1893 // Close sources.
1894 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1895 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1896 }
1897 zipped_dex_files_.clear();
1898 zip_archives_.clear();
1899 raw_dex_files_.clear();
1900 return true;
1901}
1902
David Brazdil7b49e6c2016-09-01 11:06:18 +01001903bool OatWriter::WriteDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1904 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001905 return false;
1906 }
1907 if (oat_dex_file->source_.IsZipEntry()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001908 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001909 return false;
1910 }
1911 } else if (oat_dex_file->source_.IsRawFile()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001912 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001913 return false;
1914 }
1915 } else {
1916 DCHECK(oat_dex_file->source_.IsRawData());
David Brazdil7b49e6c2016-09-01 11:06:18 +01001917 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001918 return false;
1919 }
1920 }
1921
1922 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001923 if (kIsVdexEnabled) {
1924 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
1925 vdex_size_ += oat_dex_file->dex_file_size_;
1926 } else {
1927 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
1928 oat_size_ += oat_dex_file->dex_file_size_;
1929 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001930 size_dex_file_ += oat_dex_file->dex_file_size_;
1931 return true;
1932}
1933
1934bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1935 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001936 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
1937 size_t start_offset = RoundUp(initial_offset, 4);
1938 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
1939 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001940
1941 // Seek to the start of the dex file and flush any pending operations in the stream.
1942 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001943 off_t actual_offset = out->Seek(file_offset, kSeekSet);
1944 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001945 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01001946 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001947 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1948 return false;
1949 }
1950 if (!out->Flush()) {
1951 PLOG(ERROR) << "Failed to flush before writing dex file."
1952 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1953 return false;
1954 }
1955 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001956 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001957 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01001958 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001959 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1960 return false;
1961 }
1962
David Brazdil7b49e6c2016-09-01 11:06:18 +01001963 if (kIsVdexEnabled) {
1964 vdex_size_ = start_offset;
1965 } else {
1966 oat_size_ = start_offset;
1967 }
1968 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001969 return true;
1970}
1971
David Brazdil7b49e6c2016-09-01 11:06:18 +01001972bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001973 File* file,
1974 OatDexFile* oat_dex_file,
1975 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001976 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
1977 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001978
1979 // Extract the dex file and get the extracted size.
1980 std::string error_msg;
1981 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1982 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1983 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1984 return false;
1985 }
1986 if (file->Flush() != 0) {
1987 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1988 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1989 return false;
1990 }
1991 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1992 if (extracted_end == static_cast<off_t>(-1)) {
1993 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1994 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1995 return false;
1996 }
1997 if (extracted_end < static_cast<off_t>(start_offset)) {
1998 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1999 << " Start: " << start_offset
2000 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2001 return false;
2002 }
2003 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2004 if (extracted_size < sizeof(DexFile::Header)) {
2005 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2006 << extracted_size << " File: " << oat_dex_file->GetLocation();
2007 return false;
2008 }
2009
2010 // Read the dex file header and extract required data to OatDexFile.
2011 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2012 if (actual_offset != static_cast<off_t>(start_offset)) {
2013 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2014 << " Expected: " << start_offset
2015 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2016 return false;
2017 }
2018 if (!ReadDexFileHeader(file, oat_dex_file)) {
2019 return false;
2020 }
2021 if (extracted_size < oat_dex_file->dex_file_size_) {
2022 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2023 << " file size from header: " << oat_dex_file->dex_file_size_
2024 << " File: " << oat_dex_file->GetLocation();
2025 return false;
2026 }
2027
2028 // Override the checksum from header with the CRC from ZIP entry.
2029 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2030
2031 // Seek both file and stream to the end offset.
2032 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2033 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2034 if (actual_offset != static_cast<off_t>(end_offset)) {
2035 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2036 << " Expected: " << end_offset
2037 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2038 return false;
2039 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002040 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002041 if (actual_offset != static_cast<off_t>(end_offset)) {
2042 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2043 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2044 return false;
2045 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002046 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002047 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2048 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2049 return false;
2050 }
2051
2052 // If we extracted more than the size specified in the header, truncate the file.
2053 if (extracted_size > oat_dex_file->dex_file_size_) {
2054 if (file->SetLength(end_offset) != 0) {
2055 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002056 << " File: " << oat_dex_file->GetLocation()
2057 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002058 return false;
2059 }
2060 }
2061
2062 return true;
2063}
2064
David Brazdil7b49e6c2016-09-01 11:06:18 +01002065bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002066 File* file,
2067 OatDexFile* oat_dex_file,
2068 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002069 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2070 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002071
2072 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2073 if (input_offset != static_cast<off_t>(0)) {
2074 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2075 << " Expected: 0"
2076 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2077 return false;
2078 }
2079 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2080 return false;
2081 }
2082
2083 // Copy the input dex file using sendfile().
2084 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2085 PLOG(ERROR) << "Failed to copy dex file to oat file."
2086 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2087 return false;
2088 }
2089 if (file->Flush() != 0) {
2090 PLOG(ERROR) << "Failed to flush dex file."
2091 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2092 return false;
2093 }
2094
2095 // Check file position and seek the stream to the end offset.
2096 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2097 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2098 if (actual_offset != static_cast<off_t>(end_offset)) {
2099 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2100 << " Expected: " << end_offset
2101 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2102 return false;
2103 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002104 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002105 if (actual_offset != static_cast<off_t>(end_offset)) {
2106 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2107 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2108 return false;
2109 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002110 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002111 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2112 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2113 return false;
2114 }
2115
2116 return true;
2117}
2118
David Brazdil7b49e6c2016-09-01 11:06:18 +01002119bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002120 OatDexFile* oat_dex_file,
2121 const uint8_t* dex_file) {
2122 // Note: The raw data has already been checked to contain the header
2123 // and all the data that the header specifies as the file size.
2124 DCHECK(dex_file != nullptr);
2125 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2126 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2127
David Brazdil7b49e6c2016-09-01 11:06:18 +01002128 if (!out->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002129 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002130 << " to " << out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002131 return false;
2132 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002133 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002134 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2135 << " File: " << oat_dex_file->GetLocation();
2136 return false;
2137 }
2138
2139 // Update dex file size and resize class offsets in the OatDexFile.
2140 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2141 oat_dex_file->dex_file_size_ = header->file_size_;
2142 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2143 return true;
2144}
2145
2146bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2147 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2148
David Brazdil181e1cc2016-09-01 16:38:47 +00002149 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2150 if (initial_offset == static_cast<off_t>(-1)) {
2151 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2152 return false;
2153 }
2154
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002155 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2156 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2157 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2158 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2159 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2160 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2161 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2162 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2163 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2164 return false;
2165 }
2166
2167 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2168 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2169
2170 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2171 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2172
2173 // Write OatDexFile.
2174 if (!oat_dex_file->Write(this, rodata)) {
2175 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2176 return false;
2177 }
2178 }
2179
David Brazdil181e1cc2016-09-01 16:38:47 +00002180 // Seek back to the initial position.
2181 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2182 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2183 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2184 return false;
2185 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002186
David Brazdilb92ba622016-09-01 16:00:30 +00002187 return true;
2188}
2189
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002190bool OatWriter::OpenDexFiles(
2191 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002192 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002193 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2194 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2195 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2196
2197 if (oat_dex_files_.empty()) {
2198 // Nothing to do.
2199 return true;
2200 }
2201
2202 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002203 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2204
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002205 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002206 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2207 length,
2208 PROT_READ | PROT_WRITE,
2209 MAP_SHARED,
2210 file->Fd(),
2211 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2212 /* low_4gb */ false,
2213 file->GetPath().c_str(),
2214 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002215 if (dex_files_map == nullptr) {
2216 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2217 << " error: " << error_msg;
2218 return false;
2219 }
2220 std::vector<std::unique_ptr<const DexFile>> dex_files;
2221 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2222 // Make sure no one messed with input files while we were copying data.
2223 // At the very least we need consistent file size and number of class definitions.
2224 const uint8_t* raw_dex_file =
2225 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2226 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2227 // Note: ValidateDexFileHeader() already logged an error message.
2228 LOG(ERROR) << "Failed to verify written dex file header!"
2229 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2230 << " ~ " << static_cast<const void*>(raw_dex_file);
2231 return false;
2232 }
2233 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2234 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2235 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2236 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2237 << " Output: " << file->GetPath();
2238 return false;
2239 }
2240 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2241 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2242 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2243 << " Output: " << file->GetPath();
2244 return false;
2245 }
2246
2247 // Now, open the dex file.
2248 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2249 oat_dex_file.dex_file_size_,
2250 oat_dex_file.GetLocation(),
2251 oat_dex_file.dex_file_location_checksum_,
2252 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002253 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002254 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002255 &error_msg));
2256 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002257 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2258 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002259 return false;
2260 }
2261 }
2262
2263 *opened_dex_files_map = std::move(dex_files_map);
2264 *opened_dex_files = std::move(dex_files);
2265 return true;
2266}
2267
2268bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002269 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002270 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2271 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2272
David Brazdil7b49e6c2016-09-01 11:06:18 +01002273 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2274 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2275 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2276 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2277 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2278 return false;
2279 }
2280
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002281 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2282 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2283 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002284 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2285
2286 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2287 oat_dex_file->class_offsets_.empty()) {
2288 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002289 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002290
2291 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2292 if (table_size == 0u) {
2293 continue;
2294 }
2295
2296 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002297 // TypeLookupTable allocates its own and OatDexFile takes ownership.
2298 oat_dex_file->InitTypeLookupTable(*opened_dex_files[i], /* storage */ nullptr);
2299 TypeLookupTable* table = oat_dex_file->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002300
2301 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002302 size_t initial_offset = oat_size_;
2303 size_t rodata_offset = RoundUp(initial_offset, 4);
2304 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002305
2306 if (padding_size != 0u) {
2307 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002308 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002309 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2310 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002311 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002312 return false;
2313 }
2314 }
2315
2316 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002317 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002318 DCHECK_EQ(table_size, table->RawDataLength());
2319
David Brazdil7b49e6c2016-09-01 11:06:18 +01002320 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002321 PLOG(ERROR) << "Failed to write lookup table."
2322 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002323 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002324 return false;
2325 }
2326
2327 oat_dex_file->lookup_table_offset_ = rodata_offset;
2328
David Brazdil7b49e6c2016-09-01 11:06:18 +01002329 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002330 size_oat_lookup_table_ += table_size;
2331 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002332 }
2333
David Brazdil7b49e6c2016-09-01 11:06:18 +01002334 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002335 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002336 << " File: " << oat_rodata->GetLocation();
2337 return false;
2338 }
2339
2340 return true;
2341}
2342
2343bool OatWriter::WriteVdexHeader(OutputStream* vdex_out) {
2344 off_t actual_offset = vdex_out->Seek(0, kSeekSet);
2345 if (actual_offset != 0) {
2346 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2347 << " File: " << vdex_out->GetLocation();
2348 return false;
2349 }
2350
2351 VdexFile::Header vdex_header;
2352 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2353 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002354 return false;
2355 }
2356
2357 return true;
2358}
2359
Vladimir Markof4da6752014-08-01 19:04:18 +01002360bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2361 static const uint8_t kPadding[] = {
2362 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2363 };
2364 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002365 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002366 return false;
2367 }
2368 size_code_alignment_ += aligned_code_delta;
2369 return true;
2370}
2371
Vladimir Marko944da602016-02-19 12:27:55 +00002372void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2373 DCHECK(dex_files_ != nullptr);
2374 DCHECK(relative_patcher_ != nullptr);
2375 DCHECK_NE(oat_data_offset_, 0u);
2376 if (image_writer_ != nullptr && !dex_files_->empty()) {
2377 // The oat data begin may not be initialized yet but the oat file offset is ready.
2378 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2379 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2380 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002381 }
2382}
2383
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002384OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2385 DexFileSource source,
2386 CreateTypeLookupTable create_type_lookup_table)
2387 : source_(source),
2388 create_type_lookup_table_(create_type_lookup_table),
2389 dex_file_size_(0),
2390 offset_(0),
2391 dex_file_location_size_(strlen(dex_file_location)),
2392 dex_file_location_data_(dex_file_location),
2393 dex_file_location_checksum_(0u),
2394 dex_file_offset_(0u),
2395 class_offsets_offset_(0u),
2396 lookup_table_offset_(0u),
2397 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002398}
2399
2400size_t OatWriter::OatDexFile::SizeOf() const {
2401 return sizeof(dex_file_location_size_)
2402 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002403 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002404 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002405 + sizeof(class_offsets_offset_)
2406 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002407}
2408
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002409void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2410 DCHECK_EQ(class_offsets_offset_, 0u);
2411 if (!class_offsets_.empty()) {
2412 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002413 size_t initial_offset = oat_writer->oat_size_;
2414 size_t offset = RoundUp(initial_offset, 4);
2415 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002416 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002417 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002418 }
2419}
2420
2421bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2422 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002423 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002424
Vladimir Markoe079e212016-05-25 12:49:49 +01002425 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002426 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002427 return false;
2428 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002429 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002430
Vladimir Markoe079e212016-05-25 12:49:49 +01002431 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002432 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002433 return false;
2434 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002435 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002436
Vladimir Markoe079e212016-05-25 12:49:49 +01002437 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002438 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002439 return false;
2440 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002441 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002442
Vladimir Markoe079e212016-05-25 12:49:49 +01002443 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002444 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002445 return false;
2446 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002447 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002448
Vladimir Markoe079e212016-05-25 12:49:49 +01002449 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002450 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2451 return false;
2452 }
2453 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2454
Vladimir Markoe079e212016-05-25 12:49:49 +01002455 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002456 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2457 return false;
2458 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002459 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002460
2461 return true;
2462}
2463
2464bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002465 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002466 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2467 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002468 return false;
2469 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002470 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002471 return true;
2472}
2473
Brian Carlstromba150c32013-08-27 17:31:03 -07002474OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002475 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002476 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002477 mirror::Class::Status status)
2478 : compiled_methods_(compiled_methods) {
2479 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002480 CHECK_LE(num_non_null_compiled_methods, num_methods);
2481
Brian Carlstrom265091e2013-01-30 14:08:26 -08002482 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002483 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2484
2485 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2486 // apply when there are 0 methods, we just arbitrarily say that 0
2487 // methods means kOatClassNoneCompiled and that we won't use
2488 // kOatClassAllCompiled unless there is at least one compiled
2489 // method. This means in an interpretter only system, we can assert
2490 // that all classes are kOatClassNoneCompiled.
2491 if (num_non_null_compiled_methods == 0) {
2492 type_ = kOatClassNoneCompiled;
2493 } else if (num_non_null_compiled_methods == num_methods) {
2494 type_ = kOatClassAllCompiled;
2495 } else {
2496 type_ = kOatClassSomeCompiled;
2497 }
2498
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002499 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002500 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002501 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002502
2503 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2504 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002505 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002506 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2507 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2508 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2509 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002510 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002511 method_bitmap_size_ = 0;
2512 }
2513
2514 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002515 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002516 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002517 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2518 } else {
2519 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2520 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2521 if (type_ == kOatClassSomeCompiled) {
2522 method_bitmap_->SetBit(i);
2523 }
2524 }
2525 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002526}
2527
Brian Carlstrom265091e2013-01-30 14:08:26 -08002528size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2529 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002530 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2531 if (method_offset == 0) {
2532 return 0;
2533 }
2534 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002535}
2536
2537size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2538 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002539 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002540}
2541
2542size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002543 return sizeof(status_)
2544 + sizeof(type_)
2545 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2546 + method_bitmap_size_
2547 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002548}
2549
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002550bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002551 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002552 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002553 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002554 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002555 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002556 return false;
2557 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002558 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002559
Vladimir Markoe079e212016-05-25 12:49:49 +01002560 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002561 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002562 return false;
2563 }
2564 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002565
Brian Carlstromba150c32013-08-27 17:31:03 -07002566 if (method_bitmap_size_ != 0) {
2567 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002568 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002569 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002570 return false;
2571 }
2572 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002573
Vladimir Markoe079e212016-05-25 12:49:49 +01002574 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002575 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002576 return false;
2577 }
2578 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2579 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002580
Vladimir Markoe079e212016-05-25 12:49:49 +01002581 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002582 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002583 return false;
2584 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002585 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002586 return true;
2587}
2588
Brian Carlstrome24fa612011-09-29 00:53:55 -07002589} // namespace art