blob: 5e0c64ba8bdc76fca95ce2a7ac34851ca38ae723 [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
262 private:
263 size_t GetClassOffsetsRawSize() const {
264 return class_offsets_.size() * sizeof(class_offsets_[0]);
265 }
266
267 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
268};
269
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100270#define DCHECK_OFFSET() \
271 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
272 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
273
274#define DCHECK_OFFSET_() \
275 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
276 << "file_offset=" << file_offset << " offset_=" << offset_
277
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000278OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
279 : write_state_(WriteState::kAddingDexFileSources),
280 timings_(timings),
281 raw_dex_files_(),
282 zip_archives_(),
283 zipped_dex_files_(),
284 zipped_dex_file_locations_(),
285 compiler_driver_(nullptr),
286 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800287 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000288 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100289 vdex_size_(0u),
290 vdex_dex_files_offset_(0u),
291 oat_size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000292 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100293 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700294 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100295 size_vdex_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700296 size_dex_file_alignment_(0),
297 size_executable_offset_alignment_(0),
298 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700299 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700300 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700301 size_interpreter_to_interpreter_bridge_(0),
302 size_interpreter_to_compiled_code_bridge_(0),
303 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800304 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700305 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700306 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700307 size_quick_to_interpreter_bridge_(0),
308 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100309 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700310 size_code_(0),
311 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100312 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100313 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700314 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700315 size_oat_dex_file_location_size_(0),
316 size_oat_dex_file_location_data_(0),
317 size_oat_dex_file_location_checksum_(0),
318 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000319 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000320 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000321 size_oat_lookup_table_alignment_(0),
322 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000323 size_oat_class_offsets_alignment_(0),
324 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700325 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700326 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700327 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100328 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000329 relative_patcher_(nullptr),
330 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000331}
332
333bool OatWriter::AddDexFileSource(const char* filename,
334 const char* location,
335 CreateTypeLookupTable create_type_lookup_table) {
336 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
337 uint32_t magic;
338 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700339 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
340 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000341 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
342 return false;
343 } else if (IsDexMagic(magic)) {
344 // The file is open for reading, not writing, so it's OK to let the File destructor
345 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700346 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000347 oat_dex_files_.emplace_back(location,
348 DexFileSource(raw_dex_files_.back().get()),
349 create_type_lookup_table);
350 } else if (IsZipMagic(magic)) {
351 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
352 return false;
353 }
354 } else {
355 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
356 return false;
357 }
358 return true;
359}
360
361// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700362bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000363 const char* location,
364 CreateTypeLookupTable create_type_lookup_table) {
365 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
366 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700367 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000368 ZipArchive* zip_archive = zip_archives_.back().get();
369 if (zip_archive == nullptr) {
370 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
371 << error_msg;
372 return false;
373 }
374 for (size_t i = 0; ; ++i) {
375 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
376 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
377 if (entry == nullptr) {
378 break;
379 }
380 zipped_dex_files_.push_back(std::move(entry));
381 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
382 const char* full_location = zipped_dex_file_locations_.back().c_str();
383 oat_dex_files_.emplace_back(full_location,
384 DexFileSource(zipped_dex_files_.back().get()),
385 create_type_lookup_table);
386 }
387 if (zipped_dex_file_locations_.empty()) {
388 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
389 return false;
390 }
391 return true;
392}
393
394// Add dex file source from raw memory.
395bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
396 const char* location,
397 uint32_t location_checksum,
398 CreateTypeLookupTable create_type_lookup_table) {
399 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
400 if (data.size() < sizeof(DexFile::Header)) {
401 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
402 << data.size() << " File: " << location;
403 return false;
404 }
405 if (!ValidateDexFileHeader(data.data(), location)) {
406 return false;
407 }
408 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
409 if (data.size() < header->file_size_) {
410 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
411 << " file size from header: " << header->file_size_ << " File: " << location;
412 return false;
413 }
414
415 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
416 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
417 return true;
418}
419
420dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
421 dchecked_vector<const char*> locations;
422 locations.reserve(oat_dex_files_.size());
423 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
424 locations.push_back(oat_dex_file.GetLocation());
425 }
426 return locations;
427}
428
429bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100430 File* vdex_file,
431 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000432 InstructionSet instruction_set,
433 const InstructionSetFeatures* instruction_set_features,
434 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800435 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000436 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
437 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
438 CHECK(write_state_ == WriteState::kAddingDexFileSources);
439
David Brazdil7b49e6c2016-09-01 11:06:18 +0100440 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
441 if (!RecordOatDataOffset(oat_rodata)) {
442 return false;
443 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444
445 std::unique_ptr<MemMap> dex_files_map;
446 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100447
448 // Initialize VDEX and OAT headers.
449 if (kIsVdexEnabled) {
450 size_vdex_header_ = sizeof(VdexFile::Header);
451 vdex_size_ = size_vdex_header_;
452 }
453 size_t oat_data_offset = InitOatHeader(instruction_set,
454 instruction_set_features,
455 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
456 key_value_store);
457 oat_size_ = InitOatDexFiles(oat_data_offset);
458
459 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
460
461 if (kIsVdexEnabled) {
462 std::unique_ptr<BufferedOutputStream> vdex_out(
463 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
464
465 // Write DEX files into VDEX, mmap and open them.
466 if (!WriteDexFiles(vdex_out.get(), vdex_file) ||
467 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
468 return false;
469 }
470
471 // VDEX is finalized. Seek to the beginning of the file and write the header.
472 if (!WriteVdexHeader(vdex_out.get())) {
473 return false;
474 }
475 } else {
476 // Write DEX files into OAT, mmap and open them.
477 if (!WriteDexFiles(oat_rodata, vdex_file) ||
478 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
479 return false;
480 }
481
482 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
483 // difficult because we're not using the OutputStream directly.
484 if (!oat_dex_files_.empty()) {
485 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
486 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
487 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000489
David Brazdil7b49e6c2016-09-01 11:06:18 +0100490 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000491 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
492 return false;
493 }
494
David Brazdil7b49e6c2016-09-01 11:06:18 +0100495 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000496 for (OatDexFile& oat_dex_file : oat_dex_files_) {
497 oat_dex_file.ReserveClassOffsets(this);
498 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100499
David Brazdil7b49e6c2016-09-01 11:06:18 +0100500 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000501 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
502 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000503 }
504
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000505 *opened_dex_files_map = std::move(dex_files_map);
506 *opened_dex_files = std::move(dex_files);
507 write_state_ = WriteState::kPrepareLayout;
508 return true;
509}
510
511void OatWriter::PrepareLayout(const CompilerDriver* compiler,
512 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000513 const std::vector<const DexFile*>& dex_files,
514 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000515 CHECK(write_state_ == WriteState::kPrepareLayout);
516
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000517 compiler_driver_ = compiler;
518 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000519 dex_files_ = &dex_files;
520 relative_patcher_ = relative_patcher;
521 SetMultiOatRelativePatcherAdjustment();
522
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000523 if (compiling_boot_image_) {
524 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800525 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100526 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000527 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100528
David Brazdil7b49e6c2016-09-01 11:06:18 +0100529 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800530 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000531 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800532 offset = InitOatClasses(offset);
533 }
534 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000535 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100536 offset = InitOatMaps(offset);
537 }
538 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000539 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800540 offset = InitOatCode(offset);
541 }
542 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800544 offset = InitOatCodeDexFiles(offset);
545 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100546 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700547
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800548 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100549 // Allocate space for app dex cache arrays in the .bss section.
David Brazdil7b49e6c2016-09-01 11:06:18 +0100550 size_t bss_start = RoundUp(oat_size_, kPageSize);
Andreas Gampe542451c2016-07-26 09:02:02 -0700551 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100552 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000553 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100554 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
555 DexCacheArraysLayout layout(pointer_size, dex_file);
556 bss_size_ += layout.Size();
557 }
558 }
559
Brian Carlstrome24fa612011-09-29 00:53:55 -0700560 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800561 if (compiling_boot_image_) {
562 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000563 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800564 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000565
566 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700567}
568
Ian Rogers0571d352011-11-03 19:51:38 -0700569OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700570}
571
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100572class OatWriter::DexMethodVisitor {
573 public:
574 DexMethodVisitor(OatWriter* writer, size_t offset)
575 : writer_(writer),
576 offset_(offset),
577 dex_file_(nullptr),
578 class_def_index_(DexFile::kDexNoIndex) {
579 }
580
581 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
582 DCHECK(dex_file_ == nullptr);
583 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
584 dex_file_ = dex_file;
585 class_def_index_ = class_def_index;
586 return true;
587 }
588
589 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
590
591 virtual bool EndClass() {
592 if (kIsDebugBuild) {
593 dex_file_ = nullptr;
594 class_def_index_ = DexFile::kDexNoIndex;
595 }
596 return true;
597 }
598
599 size_t GetOffset() const {
600 return offset_;
601 }
602
603 protected:
604 virtual ~DexMethodVisitor() { }
605
606 OatWriter* const writer_;
607
608 // The offset is usually advanced for each visited method by the derived class.
609 size_t offset_;
610
611 // The dex file and class def index are set in StartClass().
612 const DexFile* dex_file_;
613 size_t class_def_index_;
614};
615
616class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
617 public:
618 OatDexMethodVisitor(OatWriter* writer, size_t offset)
619 : DexMethodVisitor(writer, offset),
620 oat_class_index_(0u),
621 method_offsets_index_(0u) {
622 }
623
624 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
625 DexMethodVisitor::StartClass(dex_file, class_def_index);
626 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
627 method_offsets_index_ = 0u;
628 return true;
629 }
630
631 bool EndClass() {
632 ++oat_class_index_;
633 return DexMethodVisitor::EndClass();
634 }
635
636 protected:
637 size_t oat_class_index_;
638 size_t method_offsets_index_;
639};
640
641class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
642 public:
643 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
644 : DexMethodVisitor(writer, offset),
645 compiled_methods_(),
646 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000647 size_t num_classes = 0u;
648 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
649 num_classes += oat_dex_file.class_offsets_.size();
650 }
651 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100652 compiled_methods_.reserve(256u);
653 }
654
655 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
656 DexMethodVisitor::StartClass(dex_file, class_def_index);
657 compiled_methods_.clear();
658 num_non_null_compiled_methods_ = 0u;
659 return true;
660 }
661
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300662 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
663 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100664 // Fill in the compiled_methods_ array for methods that have a
665 // CompiledMethod. We track the number of non-null entries in
666 // num_non_null_compiled_methods_ since we only want to allocate
667 // OatMethodOffsets for the compiled methods.
668 uint32_t method_idx = it.GetMemberIndex();
669 CompiledMethod* compiled_method =
670 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
671 compiled_methods_.push_back(compiled_method);
672 if (compiled_method != nullptr) {
673 ++num_non_null_compiled_methods_;
674 }
675 return true;
676 }
677
678 bool EndClass() {
679 ClassReference class_ref(dex_file_, class_def_index_);
680 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
681 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700682 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100683 status = compiled_class->GetStatus();
684 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
685 status = mirror::Class::kStatusError;
686 } else {
687 status = mirror::Class::kStatusNotReady;
688 }
689
Vladimir Marko49b0f452015-12-10 13:49:19 +0000690 writer_->oat_classes_.emplace_back(offset_,
691 compiled_methods_,
692 num_non_null_compiled_methods_,
693 status);
694 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100695 return DexMethodVisitor::EndClass();
696 }
697
698 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000699 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100700 size_t num_non_null_compiled_methods_;
701};
702
703class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
704 public:
705 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100706 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100707 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100708 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100709 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
710 }
711
712 bool EndClass() {
713 OatDexMethodVisitor::EndClass();
714 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100715 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100716 }
717 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 }
719
720 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700721 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000722 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
724
725 if (compiled_method != nullptr) {
726 // Derived from CompiledMethod.
727 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100728
Vladimir Marko35831e82015-09-11 11:59:18 +0100729 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
730 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800731 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800732
David Srbecky009e2a62015-04-15 02:46:30 +0100733 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100734 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800735 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000736 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000737 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
738 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800739 // Duplicate methods, we want the same code for both of them so that the oat writer puts
740 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800741 } else {
742 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100743 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800744 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000745 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100746 quick_code_offset = dedupe_map_.GetOrCreate(
747 compiled_method,
748 [this, &deduped, compiled_method, &it, thumb_offset]() {
749 deduped = false;
750 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
751 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800752 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100753
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100754 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000755 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100756 // TODO: Should this be a hard failure?
757 LOG(WARNING) << "Multiple definitions of "
758 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000759 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
760 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100761 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000762 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100763 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800764 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100765
Elliott Hughes956af0f2014-12-11 14:34:28 -0800766 // Update quick method header.
767 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
768 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800769 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100770 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
771 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100772 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800773 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
774 // to 0-offset and we need to adjust it by code_offset.
775 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100776 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800777 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100778 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800779 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800780 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
781 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
782 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100783 *method_header = OatQuickMethodHeader(vmap_table_offset,
784 frame_size_in_bytes,
785 core_spill_mask,
786 fp_spill_mask,
787 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100788
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000789 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800790 // Update offsets. (Checksum is updated when writing.)
791 offset_ += sizeof(*method_header); // Method header is prepended before code.
792 offset_ += code_size;
793 // Record absolute patch locations.
794 if (!compiled_method->GetPatches().empty()) {
795 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
796 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000797 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100798 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100799 }
800 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100801 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800802 }
Alex Light78382fa2014-06-06 15:45:32 -0700803
David Srbecky91cc06c2016-03-07 16:13:58 +0000804 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000805 // Exclude quickened dex methods (code_size == 0) since they have no native code.
806 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
807 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800808 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000809 debug::MethodDebugInfo info = debug::MethodDebugInfo();
810 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000811 info.dex_file = dex_file_;
812 info.class_def_index = class_def_index_;
813 info.dex_method_index = it.GetMemberIndex();
814 info.access_flags = it.GetMethodAccessFlags();
815 info.code_item = it.GetMethodCodeItem();
816 info.isa = compiled_method->GetInstructionSet();
817 info.deduped = deduped;
818 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
819 info.is_optimized = method_header->IsOptimized();
820 info.is_code_address_text_relative = true;
821 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
822 info.code_size = code_size;
823 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
824 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
825 info.cfi = compiled_method->GetCFIInfo();
826 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100827 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100828
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100829 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
830 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
831 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832 ++method_offsets_index_;
833 }
834
835 return true;
836 }
837
838 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000839 struct CodeOffsetsKeyComparator {
840 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100841 // Code is deduplicated by CompilerDriver, compare only data pointers.
842 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
843 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000844 }
845 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100846 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
847 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000848 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100849 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
850 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000851 }
852 return false;
853 }
854 };
855
David Srbecky009e2a62015-04-15 02:46:30 +0100856 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
857 const ClassDataItemIterator& it,
858 uint32_t thumb_offset) {
859 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100860 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100861 offset_ += CodeAlignmentSize(offset_, *compiled_method);
862 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100863 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
864 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
865 }
866
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100867 // Deduplication is already done on a pointer basis by the compiler driver,
868 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100869 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100870
David Srbecky009e2a62015-04-15 02:46:30 +0100871 // Cache of compiler's --debuggable option.
872 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100873};
874
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100875class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
876 public:
877 InitMapMethodVisitor(OatWriter* writer, size_t offset)
878 : OatDexMethodVisitor(writer, offset) {
879 }
880
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700881 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700882 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000883 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100884 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
885
886 if (compiled_method != nullptr) {
887 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100888 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100889
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100890 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100891 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100892 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100893 size_t offset = dedupe_map_.GetOrCreate(
894 map.data(),
895 [this, map_size]() {
896 uint32_t new_offset = offset_;
897 offset_ += map_size;
898 return new_offset;
899 });
900 // Code offset is not initialized yet, so set the map offset to 0u-offset.
901 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
902 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 }
904 ++method_offsets_index_;
905 }
906
907 return true;
908 }
909
910 private:
911 // Deduplication is already done on a pointer basis by the compiler driver,
912 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100913 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100914};
915
916class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
917 public:
918 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800919 : OatDexMethodVisitor(writer, offset),
920 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100921 }
922
923 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700924 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800925 const DexFile::TypeId& type_id =
926 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
927 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
928 // Skip methods that are not in the image.
929 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
930 return true;
931 }
932
Vladimir Marko49b0f452015-12-10 13:49:19 +0000933 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100934 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
935
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800936 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100937 if (compiled_method != nullptr) {
938 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
939 offsets = oat_class->method_offsets_[method_offsets_index_];
940 ++method_offsets_index_;
941 }
942
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100943 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100944 // Unchecked as we hold mutator_lock_ on entry.
945 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800946 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700947 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
948 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800949 ArtMethod* method;
950 if (writer_->HasBootImage()) {
951 const InvokeType invoke_type = it.GetMethodInvokeType(
952 dex_file_->GetClassDef(class_def_index_));
953 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
954 *dex_file_,
955 it.GetMemberIndex(),
956 dex_cache,
957 ScopedNullHandle<mirror::ClassLoader>(),
958 nullptr,
959 invoke_type);
960 if (method == nullptr) {
961 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
962 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
963 soa.Self()->AssertPendingException();
964 mirror::Throwable* exc = soa.Self()->GetException();
965 std::string dump = exc->Dump();
966 LOG(FATAL) << dump;
967 UNREACHABLE();
968 }
969 } else {
970 // Should already have been resolved by the compiler, just peek into the dex cache.
971 // It may not be resolved if the class failed to verify, in this case, don't set the
972 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
973 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700974 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800975 if (method != nullptr &&
976 compiled_method != nullptr &&
977 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100978 method->SetEntryPointFromQuickCompiledCodePtrSize(
979 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
980 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100981
982 return true;
983 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800984
985 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -0700986 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100987};
988
989class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
990 public:
991 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100992 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100993 : OatDexMethodVisitor(writer, relative_offset),
994 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100995 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100996 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -0700997 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100998 class_linker_(Runtime::Current()->GetClassLinker()),
999 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001000 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001001 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001002 // If we're creating the image, the address space must be ready so that we can apply patches.
1003 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001004 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001005 }
1006
Vladimir Markof4da6752014-08-01 19:04:18 +01001007 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001008 }
1009
1010 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001011 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001012 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1013 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001014 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001015 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001016 }
1017 return true;
1018 }
1019
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001020 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001021 bool result = OatDexMethodVisitor::EndClass();
1022 if (oat_class_index_ == writer_->oat_classes_.size()) {
1023 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001024 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001025 if (UNLIKELY(offset_ == 0u)) {
1026 PLOG(ERROR) << "Failed to write final relative call thunks";
1027 result = false;
1028 }
1029 }
1030 return result;
1031 }
1032
1033 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001034 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001035 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001036 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1037
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001038 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001039 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001040 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001041 size_t file_offset = file_offset_;
1042 OutputStream* out = out_;
1043
Vladimir Marko35831e82015-09-11 11:59:18 +01001044 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1045 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001046
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001047 // Deduplicate code arrays.
1048 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1049 if (method_offsets.code_offset_ > offset_) {
1050 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1051 if (offset_ == 0u) {
1052 ReportWriteFailure("relative call thunk", it);
1053 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001054 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001055 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1056 if (alignment_size != 0) {
1057 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001058 ReportWriteFailure("code alignment padding", it);
1059 return false;
1060 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001061 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001062 DCHECK_OFFSET_();
1063 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001064 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001065 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1066 DCHECK_EQ(method_offsets.code_offset_,
1067 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1068 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1069 const OatQuickMethodHeader& method_header =
1070 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001071 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001072 ReportWriteFailure("method header", it);
1073 return false;
1074 }
1075 writer_->size_method_header_ += sizeof(method_header);
1076 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001077 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001078
1079 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001080 patched_code_.assign(quick_code.begin(), quick_code.end());
1081 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001082 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001083 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001084 switch (patch.GetType()) {
1085 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001086 // NOTE: Relative calls across oat files are not supported.
1087 uint32_t target_offset = GetTargetOffset(patch);
1088 writer_->relative_patcher_->PatchCall(&patched_code_,
1089 literal_offset,
1090 offset_ + literal_offset,
1091 target_offset);
1092 break;
1093 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001094 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001095 uint32_t target_offset = GetDexCacheOffset(patch);
1096 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1097 patch,
1098 offset_ + literal_offset,
1099 target_offset);
1100 break;
1101 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001102 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001103 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1104 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1105 patch,
1106 offset_ + literal_offset,
1107 target_offset);
1108 break;
1109 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001110 case LinkerPatch::Type::kTypeRelative: {
1111 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1112 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1113 patch,
1114 offset_ + literal_offset,
1115 target_offset);
1116 break;
1117 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001118 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001119 uint32_t target_offset = GetTargetOffset(patch);
1120 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1121 break;
1122 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001123 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001124 ArtMethod* method = GetTargetMethod(patch);
1125 PatchMethodAddress(&patched_code_, literal_offset, method);
1126 break;
1127 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001128 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001129 mirror::String* string = GetTargetString(patch);
1130 PatchObjectAddress(&patched_code_, literal_offset, string);
1131 break;
1132 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001133 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001134 mirror::Class* type = GetTargetType(patch);
1135 PatchObjectAddress(&patched_code_, literal_offset, type);
1136 break;
1137 }
1138 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001139 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001140 break;
1141 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001142 }
1143 }
1144 }
1145
Vladimir Markoe079e212016-05-25 12:49:49 +01001146 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001147 ReportWriteFailure("method code", it);
1148 return false;
1149 }
1150 writer_->size_code_ += code_size;
1151 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001152 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001153 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001154 ++method_offsets_index_;
1155 }
1156
1157 return true;
1158 }
1159
1160 private:
1161 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001162 const size_t file_offset_;
1163 const ScopedObjectAccess soa_;
1164 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001165 ClassLinker* const class_linker_;
1166 mirror::DexCache* dex_cache_;
1167 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001168
1169 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1170 PLOG(ERROR) << "Failed to write " << what << " for "
1171 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1172 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001173
Mathieu Chartiere401d142015-04-22 13:56:20 -07001174 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001175 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001176 MethodReference ref = patch.TargetMethod();
1177 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001178 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1179 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001180 ArtMethod* method = dex_cache->GetResolvedMethod(
1181 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001182 CHECK(method != nullptr);
1183 return method;
1184 }
1185
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001186 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001187 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1188 // If there's no new compiled code, either we're compiling an app and the target method
1189 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001190 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001191 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001192 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001193 PointerSize size =
1194 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001195 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1196 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001197 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001198 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1199 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1200 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1201 target_offset = PointerToLowMemUInt32(oat_code_offset);
1202 } else {
1203 target_offset = target->IsNative()
1204 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1205 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1206 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001207 }
1208 return target_offset;
1209 }
1210
Vladimir Marko052164a2016-04-27 13:54:18 +01001211 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001212 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001213 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001214 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001215 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1216 }
1217
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001218 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001219 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001220 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1221 CHECK(type != nullptr);
1222 return type;
1223 }
1224
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001225 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001226 ScopedObjectAccessUnchecked soa(Thread::Current());
1227 StackHandleScope<1> hs(soa.Self());
1228 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1229 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1230 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1231 patch.TargetStringIndex(),
1232 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001233 DCHECK(string != nullptr);
1234 DCHECK(writer_->HasBootImage() ||
1235 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1236 return string;
1237 }
1238
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001239 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001240 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001241 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1242 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1243 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1244 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001245 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001246 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001247 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1248 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001249 }
1250 }
1251
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001252 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001253 DCHECK(writer_->HasBootImage());
1254 object = writer_->image_writer_->GetImageAddress(object);
1255 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1256 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1257 // TODO: Clean up offset types. The target offset must be treated as signed.
1258 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1259 }
1260
Vladimir Markof4da6752014-08-01 19:04:18 +01001261 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001262 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001263 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001264 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001265 } else {
1266 // NOTE: We're using linker patches for app->boot references when the image can
1267 // be relocated and therefore we need to emit .oat_patches. We're not using this
1268 // for app->app references, so check that the object is in the image space.
1269 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001270 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001271 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001272 uint32_t address = PointerToLowMemUInt32(object);
1273 DCHECK_LE(offset + 4, code->size());
1274 uint8_t* data = &(*code)[offset];
1275 data[0] = address & 0xffu;
1276 data[1] = (address >> 8) & 0xffu;
1277 data[2] = (address >> 16) & 0xffu;
1278 data[3] = (address >> 24) & 0xffu;
1279 }
1280
Mathieu Chartiere401d142015-04-22 13:56:20 -07001281 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001282 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001283 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001284 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001285 } else if (kIsDebugBuild) {
1286 // NOTE: We're using linker patches for app->boot references when the image can
1287 // be relocated and therefore we need to emit .oat_patches. We're not using this
1288 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001289 std::vector<gc::space::ImageSpace*> image_spaces =
1290 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1291 bool contains_method = false;
1292 for (gc::space::ImageSpace* image_space : image_spaces) {
1293 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1294 contains_method |=
1295 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1296 }
1297 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001298 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001299 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 uint32_t address = PointerToLowMemUInt32(method);
1301 DCHECK_LE(offset + 4, code->size());
1302 uint8_t* data = &(*code)[offset];
1303 data[0] = address & 0xffu;
1304 data[1] = (address >> 8) & 0xffu;
1305 data[2] = (address >> 16) & 0xffu;
1306 data[3] = (address >> 24) & 0xffu;
1307 }
1308
Vladimir Markof4da6752014-08-01 19:04:18 +01001309 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001310 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001311 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001312 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001313 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1314 // TODO: Clean up offset types.
1315 // The target_offset must be treated as signed for cross-oat patching.
1316 const void* target = reinterpret_cast<const void*>(
1317 writer_->image_writer_->GetOatDataBegin(oat_index) +
1318 static_cast<int32_t>(target_offset));
1319 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001320 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001321 DCHECK_LE(offset + 4, code->size());
1322 uint8_t* data = &(*code)[offset];
1323 data[0] = address & 0xffu;
1324 data[1] = (address >> 8) & 0xffu;
1325 data[2] = (address >> 16) & 0xffu;
1326 data[3] = (address >> 24) & 0xffu;
1327 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001328};
1329
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001330class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1331 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001332 WriteMapMethodVisitor(OatWriter* writer,
1333 OutputStream* out,
1334 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001335 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001336 : OatDexMethodVisitor(writer, relative_offset),
1337 out_(out),
1338 file_offset_(file_offset) {
1339 }
1340
1341 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001342 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001343 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1344
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001345 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001346 size_t file_offset = file_offset_;
1347 OutputStream* out = out_;
1348
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001349 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1350 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001351 ++method_offsets_index_;
1352
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001353 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1354 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1355 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1356 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1357
1358 if (map_offset != 0u) {
1359 // Transform map_offset to actual oat data offset.
1360 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1361 DCHECK_NE(map_offset, 0u);
1362 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1363
1364 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1365 size_t map_size = map.size() * sizeof(map[0]);
1366 if (map_offset == offset_) {
1367 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001368 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001369 ReportWriteFailure(it);
1370 return false;
1371 }
1372 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001373 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001374 }
1375 DCHECK_OFFSET_();
1376 }
1377
1378 return true;
1379 }
1380
1381 private:
1382 OutputStream* const out_;
1383 size_t const file_offset_;
1384
1385 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001386 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001387 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1388 }
1389};
1390
1391// Visit all methods from all classes in all dex files with the specified visitor.
1392bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1393 for (const DexFile* dex_file : *dex_files_) {
1394 const size_t class_def_count = dex_file->NumClassDefs();
1395 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1396 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1397 return false;
1398 }
1399 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001400 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001401 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001402 ClassDataItemIterator it(*dex_file, class_data);
1403 while (it.HasNextStaticField()) {
1404 it.Next();
1405 }
1406 while (it.HasNextInstanceField()) {
1407 it.Next();
1408 }
1409 size_t class_def_method_index = 0u;
1410 while (it.HasNextDirectMethod()) {
1411 if (!visitor->VisitMethod(class_def_method_index, it)) {
1412 return false;
1413 }
1414 ++class_def_method_index;
1415 it.Next();
1416 }
1417 while (it.HasNextVirtualMethod()) {
1418 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1419 return false;
1420 }
1421 ++class_def_method_index;
1422 it.Next();
1423 }
1424 }
1425 if (UNLIKELY(!visitor->EndClass())) {
1426 return false;
1427 }
1428 }
1429 }
1430 return true;
1431}
1432
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001433size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1434 const InstructionSetFeatures* instruction_set_features,
1435 uint32_t num_dex_files,
1436 SafeMap<std::string, std::string>* key_value_store) {
1437 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1438 oat_header_.reset(OatHeader::Create(instruction_set,
1439 instruction_set_features,
1440 num_dex_files,
1441 key_value_store));
1442 size_oat_header_ += sizeof(OatHeader);
1443 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001444 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001445}
1446
1447size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001448 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1449 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001450 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001451 oat_dex_file.offset_ = offset;
1452 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001453 }
1454 return offset;
1455}
1456
Brian Carlstrom389efb02012-01-11 12:06:26 -08001457size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001458 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001459 InitOatClassesMethodVisitor visitor(this, offset);
1460 bool success = VisitDexMethods(&visitor);
1461 CHECK(success);
1462 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001463
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001464 // Update oat_dex_files_.
1465 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001466 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1467 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001469 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001470 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001471 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001472 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001473 CHECK(oat_class_it == oat_classes_.end());
1474
1475 return offset;
1476}
1477
1478size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001479 InitMapMethodVisitor visitor(this, offset);
1480 bool success = VisitDexMethods(&visitor);
1481 DCHECK(success);
1482 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001483
Brian Carlstrome24fa612011-09-29 00:53:55 -07001484 return offset;
1485}
1486
1487size_t OatWriter::InitOatCode(size_t offset) {
1488 // calculate the offsets within OatHeader to executable code
1489 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001490 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001491 // required to be on a new page boundary
1492 offset = RoundUp(offset, kPageSize);
1493 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001494 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001495 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001496 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001497
Ian Rogers848871b2013-08-05 10:56:33 -07001498 #define DO_TRAMPOLINE(field, fn_name) \
1499 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001500 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1501 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001502 (field) = compiler_driver_->Create ## fn_name(); \
1503 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001504
Ian Rogers848871b2013-08-05 10:56:33 -07001505 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001506 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001507 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001508 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1509 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001510
Ian Rogers848871b2013-08-05 10:56:33 -07001511 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001512 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001513 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1514 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1515 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001516 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001517 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001518 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001519 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001520 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001521 return offset;
1522}
1523
1524size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001525 #define VISIT(VisitorType) \
1526 do { \
1527 VisitorType visitor(this, offset); \
1528 bool success = VisitDexMethods(&visitor); \
1529 DCHECK(success); \
1530 offset = visitor.GetOffset(); \
1531 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001532
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001533 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001534 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001535 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001536 }
Logan Chien8b977d32012-02-21 19:14:55 +08001537
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001538 #undef VISIT
1539
Brian Carlstrome24fa612011-09-29 00:53:55 -07001540 return offset;
1541}
1542
David Srbeckybc90fd02015-04-22 19:40:27 +01001543bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001544 CHECK(write_state_ == WriteState::kWriteRoData);
1545
Vladimir Markoe079e212016-05-25 12:49:49 +01001546 // Wrap out to update checksum with each write.
1547 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1548 out = &checksum_updating_out;
1549
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001550 if (!WriteClassOffsets(out)) {
1551 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001552 return false;
1553 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001554
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001555 if (!WriteClasses(out)) {
1556 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001557 return false;
1558 }
1559
Vladimir Markof4da6752014-08-01 19:04:18 +01001560 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001561 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001562 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001563 return false;
1564 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001565 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001566 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001567 relative_offset = WriteMaps(out, file_offset, relative_offset);
1568 if (relative_offset == 0) {
1569 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1570 return false;
1571 }
1572
David Srbeckybc90fd02015-04-22 19:40:27 +01001573 // Write padding.
1574 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1575 relative_offset += size_executable_offset_alignment_;
1576 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1577 size_t expected_file_offset = file_offset + relative_offset;
1578 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1579 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1580 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1581 return 0;
1582 }
1583 DCHECK_OFFSET();
1584
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001585 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001586 return true;
1587}
1588
1589bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001590 CHECK(write_state_ == WriteState::kWriteText);
1591
Vladimir Markoe079e212016-05-25 12:49:49 +01001592 // Wrap out to update checksum with each write.
1593 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1594 out = &checksum_updating_out;
1595
Vladimir Marko944da602016-02-19 12:27:55 +00001596 SetMultiOatRelativePatcherAdjustment();
1597
David Srbeckybc90fd02015-04-22 19:40:27 +01001598 const size_t file_offset = oat_data_offset_;
1599 size_t relative_offset = oat_header_->GetExecutableOffset();
1600 DCHECK_OFFSET();
1601
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001602 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001603 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001604 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001605 return false;
1606 }
1607
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001608 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1609 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001610 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001611 return false;
1612 }
1613
Vladimir Markof4da6752014-08-01 19:04:18 +01001614 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001615 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001616 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1617 return false;
1618 }
1619
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001620 if (kIsDebugBuild) {
1621 uint32_t size_total = 0;
1622 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001623 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1624 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001625
David Brazdil7b49e6c2016-09-01 11:06:18 +01001626 DO_STAT(size_vdex_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001627 DO_STAT(size_dex_file_alignment_);
1628 DO_STAT(size_executable_offset_alignment_);
1629 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001630 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001631 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001632 DO_STAT(size_interpreter_to_interpreter_bridge_);
1633 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1634 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001635 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001636 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001637 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001638 DO_STAT(size_quick_to_interpreter_bridge_);
1639 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001640 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001641 DO_STAT(size_code_);
1642 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001643 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001644 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001645 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001646 DO_STAT(size_oat_dex_file_location_size_);
1647 DO_STAT(size_oat_dex_file_location_data_);
1648 DO_STAT(size_oat_dex_file_location_checksum_);
1649 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001650 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001651 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001652 DO_STAT(size_oat_lookup_table_alignment_);
1653 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001654 DO_STAT(size_oat_class_offsets_alignment_);
1655 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001656 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001657 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001658 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001659 DO_STAT(size_oat_class_method_offsets_);
1660 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001661
David Brazdil7b49e6c2016-09-01 11:06:18 +01001662 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1663
1664 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1665 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001666 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001667
David Brazdil7b49e6c2016-09-01 11:06:18 +01001668 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1669 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001670
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001671 write_state_ = WriteState::kWriteHeader;
1672 return true;
1673}
1674
1675bool OatWriter::WriteHeader(OutputStream* out,
1676 uint32_t image_file_location_oat_checksum,
1677 uintptr_t image_file_location_oat_begin,
1678 int32_t image_patch_delta) {
1679 CHECK(write_state_ == WriteState::kWriteHeader);
1680
1681 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1682 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1683 if (compiler_driver_->IsBootImage()) {
1684 CHECK_EQ(image_patch_delta, 0);
1685 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1686 } else {
1687 CHECK_ALIGNED(image_patch_delta, kPageSize);
1688 oat_header_->SetImagePatchDelta(image_patch_delta);
1689 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001690 oat_header_->UpdateChecksumWithHeaderData();
1691
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001692 const size_t file_offset = oat_data_offset_;
1693
1694 off_t current_offset = out->Seek(0, kSeekCurrent);
1695 if (current_offset == static_cast<off_t>(-1)) {
1696 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1697 return false;
1698 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001699 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001700 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1701 return false;
1702 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001703 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001704
1705 // Flush all other data before writing the header.
1706 if (!out->Flush()) {
1707 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1708 return false;
1709 }
1710 // Write the header.
1711 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001712 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001713 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1714 return false;
1715 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001716 // Flush the header data.
1717 if (!out->Flush()) {
1718 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001719 return false;
1720 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001721
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001722 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1723 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1724 return false;
1725 }
1726 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1727
1728 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001729 return true;
1730}
1731
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001732bool OatWriter::WriteClassOffsets(OutputStream* out) {
1733 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1734 if (oat_dex_file.class_offsets_offset_ != 0u) {
1735 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1736 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1737 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1738 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1739 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001740 return false;
1741 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001742 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1743 return false;
1744 }
1745 }
1746 }
1747 return true;
1748}
1749
1750bool OatWriter::WriteClasses(OutputStream* out) {
1751 for (OatClass& oat_class : oat_classes_) {
1752 if (!oat_class.Write(this, out, oat_data_offset_)) {
1753 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1754 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001755 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001756 }
1757 return true;
1758}
1759
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001760size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001761 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001762 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1763 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1764 return 0;
1765 }
1766 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001767 size_vmap_table_ = relative_offset - vmap_tables_offset;
1768
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001769 return relative_offset;
1770}
1771
1772size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001773 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001774 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001775
Ian Rogers848871b2013-08-05 10:56:33 -07001776 #define DO_TRAMPOLINE(field) \
1777 do { \
1778 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1779 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001780 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001781 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001782 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001783 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001784 return false; \
1785 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001786 size_ ## field += (field)->size(); \
1787 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001788 DCHECK_OFFSET(); \
1789 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001790
Ian Rogers848871b2013-08-05 10:56:33 -07001791 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001792 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001793 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001794 DO_TRAMPOLINE(quick_resolution_trampoline_);
1795 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1796 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001797 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001798 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001799}
1800
Ian Rogers3d504072014-03-01 09:16:49 -08001801size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001802 const size_t file_offset,
1803 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001804 #define VISIT(VisitorType) \
1805 do { \
1806 VisitorType visitor(this, out, file_offset, relative_offset); \
1807 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1808 return 0; \
1809 } \
1810 relative_offset = visitor.GetOffset(); \
1811 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001812
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001813 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001814
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001815 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001816
Vladimir Markob163bb72015-03-31 21:49:49 +01001817 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1818 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1819 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1820
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001821 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001822}
1823
Vladimir Marko944da602016-02-19 12:27:55 +00001824bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001825 // Get the elf file offset of the oat file.
1826 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1827 if (raw_file_offset == static_cast<off_t>(-1)) {
1828 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1829 return false;
1830 }
1831 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1832 return true;
1833}
1834
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001835bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1836 // Read the dex file header and perform minimal verification.
1837 uint8_t raw_header[sizeof(DexFile::Header)];
1838 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1839 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1840 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1841 return false;
1842 }
1843 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1844 return false;
1845 }
1846
1847 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1848 oat_dex_file->dex_file_size_ = header->file_size_;
1849 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1850 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1851 return true;
1852}
1853
1854bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1855 if (!DexFile::IsMagicValid(raw_header)) {
1856 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1857 return false;
1858 }
1859 if (!DexFile::IsVersionValid(raw_header)) {
1860 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1861 return false;
1862 }
1863 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1864 if (header->file_size_ < sizeof(DexFile::Header)) {
1865 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1866 << " File: " << location;
1867 return false;
1868 }
1869 return true;
1870}
1871
David Brazdil7b49e6c2016-09-01 11:06:18 +01001872bool OatWriter::WriteDexFiles(OutputStream* out, File* file) {
1873 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001874
David Brazdil7b49e6c2016-09-01 11:06:18 +01001875 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001876
1877 // Write dex files.
1878 for (OatDexFile& oat_dex_file : oat_dex_files_) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001879 if (!WriteDexFile(out, file, &oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001880 return false;
1881 }
1882 }
1883
1884 // Close sources.
1885 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1886 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1887 }
1888 zipped_dex_files_.clear();
1889 zip_archives_.clear();
1890 raw_dex_files_.clear();
1891 return true;
1892}
1893
David Brazdil7b49e6c2016-09-01 11:06:18 +01001894bool OatWriter::WriteDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1895 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001896 return false;
1897 }
1898 if (oat_dex_file->source_.IsZipEntry()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001899 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001900 return false;
1901 }
1902 } else if (oat_dex_file->source_.IsRawFile()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001903 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001904 return false;
1905 }
1906 } else {
1907 DCHECK(oat_dex_file->source_.IsRawData());
David Brazdil7b49e6c2016-09-01 11:06:18 +01001908 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001909 return false;
1910 }
1911 }
1912
1913 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001914 if (kIsVdexEnabled) {
1915 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
1916 vdex_size_ += oat_dex_file->dex_file_size_;
1917 } else {
1918 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
1919 oat_size_ += oat_dex_file->dex_file_size_;
1920 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001921 size_dex_file_ += oat_dex_file->dex_file_size_;
1922 return true;
1923}
1924
1925bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1926 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001927 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
1928 size_t start_offset = RoundUp(initial_offset, 4);
1929 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
1930 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001931
1932 // Seek to the start of the dex file and flush any pending operations in the stream.
1933 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001934 off_t actual_offset = out->Seek(file_offset, kSeekSet);
1935 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001936 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01001937 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001938 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1939 return false;
1940 }
1941 if (!out->Flush()) {
1942 PLOG(ERROR) << "Failed to flush before writing dex file."
1943 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1944 return false;
1945 }
1946 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001947 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001948 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01001949 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001950 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1951 return false;
1952 }
1953
David Brazdil7b49e6c2016-09-01 11:06:18 +01001954 if (kIsVdexEnabled) {
1955 vdex_size_ = start_offset;
1956 } else {
1957 oat_size_ = start_offset;
1958 }
1959 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001960 return true;
1961}
1962
David Brazdil7b49e6c2016-09-01 11:06:18 +01001963bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001964 File* file,
1965 OatDexFile* oat_dex_file,
1966 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001967 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
1968 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001969
1970 // Extract the dex file and get the extracted size.
1971 std::string error_msg;
1972 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1973 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1974 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1975 return false;
1976 }
1977 if (file->Flush() != 0) {
1978 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1979 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1980 return false;
1981 }
1982 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1983 if (extracted_end == static_cast<off_t>(-1)) {
1984 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1985 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1986 return false;
1987 }
1988 if (extracted_end < static_cast<off_t>(start_offset)) {
1989 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1990 << " Start: " << start_offset
1991 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1992 return false;
1993 }
1994 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1995 if (extracted_size < sizeof(DexFile::Header)) {
1996 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1997 << extracted_size << " File: " << oat_dex_file->GetLocation();
1998 return false;
1999 }
2000
2001 // Read the dex file header and extract required data to OatDexFile.
2002 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2003 if (actual_offset != static_cast<off_t>(start_offset)) {
2004 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2005 << " Expected: " << start_offset
2006 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2007 return false;
2008 }
2009 if (!ReadDexFileHeader(file, oat_dex_file)) {
2010 return false;
2011 }
2012 if (extracted_size < oat_dex_file->dex_file_size_) {
2013 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2014 << " file size from header: " << oat_dex_file->dex_file_size_
2015 << " File: " << oat_dex_file->GetLocation();
2016 return false;
2017 }
2018
2019 // Override the checksum from header with the CRC from ZIP entry.
2020 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2021
2022 // Seek both file and stream to the end offset.
2023 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2024 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2025 if (actual_offset != static_cast<off_t>(end_offset)) {
2026 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2027 << " Expected: " << end_offset
2028 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2029 return false;
2030 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002031 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002032 if (actual_offset != static_cast<off_t>(end_offset)) {
2033 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2034 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2035 return false;
2036 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002037 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002038 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2039 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2040 return false;
2041 }
2042
2043 // If we extracted more than the size specified in the header, truncate the file.
2044 if (extracted_size > oat_dex_file->dex_file_size_) {
2045 if (file->SetLength(end_offset) != 0) {
2046 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002047 << " File: " << oat_dex_file->GetLocation()
2048 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002049 return false;
2050 }
2051 }
2052
2053 return true;
2054}
2055
David Brazdil7b49e6c2016-09-01 11:06:18 +01002056bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002057 File* file,
2058 OatDexFile* oat_dex_file,
2059 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002060 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2061 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002062
2063 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2064 if (input_offset != static_cast<off_t>(0)) {
2065 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2066 << " Expected: 0"
2067 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2068 return false;
2069 }
2070 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2071 return false;
2072 }
2073
2074 // Copy the input dex file using sendfile().
2075 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2076 PLOG(ERROR) << "Failed to copy dex file to oat file."
2077 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2078 return false;
2079 }
2080 if (file->Flush() != 0) {
2081 PLOG(ERROR) << "Failed to flush dex file."
2082 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2083 return false;
2084 }
2085
2086 // Check file position and seek the stream to the end offset.
2087 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2088 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2089 if (actual_offset != static_cast<off_t>(end_offset)) {
2090 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2091 << " Expected: " << end_offset
2092 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2093 return false;
2094 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002095 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002096 if (actual_offset != static_cast<off_t>(end_offset)) {
2097 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2098 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2099 return false;
2100 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002101 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002102 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2103 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2104 return false;
2105 }
2106
2107 return true;
2108}
2109
David Brazdil7b49e6c2016-09-01 11:06:18 +01002110bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002111 OatDexFile* oat_dex_file,
2112 const uint8_t* dex_file) {
2113 // Note: The raw data has already been checked to contain the header
2114 // and all the data that the header specifies as the file size.
2115 DCHECK(dex_file != nullptr);
2116 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2117 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2118
David Brazdil7b49e6c2016-09-01 11:06:18 +01002119 if (!out->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002120 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002121 << " to " << out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002122 return false;
2123 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002124 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002125 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2126 << " File: " << oat_dex_file->GetLocation();
2127 return false;
2128 }
2129
2130 // Update dex file size and resize class offsets in the OatDexFile.
2131 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2132 oat_dex_file->dex_file_size_ = header->file_size_;
2133 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2134 return true;
2135}
2136
2137bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2138 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2139
David Brazdil181e1cc2016-09-01 16:38:47 +00002140 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2141 if (initial_offset == static_cast<off_t>(-1)) {
2142 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2143 return false;
2144 }
2145
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002146 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2147 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2148 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2149 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2150 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2151 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2152 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2153 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2154 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2155 return false;
2156 }
2157
2158 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2159 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2160
2161 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2162 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2163
2164 // Write OatDexFile.
2165 if (!oat_dex_file->Write(this, rodata)) {
2166 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2167 return false;
2168 }
2169 }
2170
David Brazdil181e1cc2016-09-01 16:38:47 +00002171 // Seek back to the initial position.
2172 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2173 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2174 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2175 return false;
2176 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002177
David Brazdilb92ba622016-09-01 16:00:30 +00002178 return true;
2179}
2180
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002181bool OatWriter::OpenDexFiles(
2182 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002183 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002184 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2185 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2186 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2187
2188 if (oat_dex_files_.empty()) {
2189 // Nothing to do.
2190 return true;
2191 }
2192
2193 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002194 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2195
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002196 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002197 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2198 length,
2199 PROT_READ | PROT_WRITE,
2200 MAP_SHARED,
2201 file->Fd(),
2202 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2203 /* low_4gb */ false,
2204 file->GetPath().c_str(),
2205 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002206 if (dex_files_map == nullptr) {
2207 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2208 << " error: " << error_msg;
2209 return false;
2210 }
2211 std::vector<std::unique_ptr<const DexFile>> dex_files;
2212 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2213 // Make sure no one messed with input files while we were copying data.
2214 // At the very least we need consistent file size and number of class definitions.
2215 const uint8_t* raw_dex_file =
2216 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2217 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2218 // Note: ValidateDexFileHeader() already logged an error message.
2219 LOG(ERROR) << "Failed to verify written dex file header!"
2220 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2221 << " ~ " << static_cast<const void*>(raw_dex_file);
2222 return false;
2223 }
2224 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2225 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2226 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2227 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2228 << " Output: " << file->GetPath();
2229 return false;
2230 }
2231 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2232 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2233 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2234 << " Output: " << file->GetPath();
2235 return false;
2236 }
2237
2238 // Now, open the dex file.
2239 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2240 oat_dex_file.dex_file_size_,
2241 oat_dex_file.GetLocation(),
2242 oat_dex_file.dex_file_location_checksum_,
2243 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002244 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002245 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002246 &error_msg));
2247 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002248 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2249 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002250 return false;
2251 }
2252 }
2253
2254 *opened_dex_files_map = std::move(dex_files_map);
2255 *opened_dex_files = std::move(dex_files);
2256 return true;
2257}
2258
2259bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002260 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002261 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2262 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2263
David Brazdil7b49e6c2016-09-01 11:06:18 +01002264 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2265 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2266 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2267 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2268 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2269 return false;
2270 }
2271
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002272 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2273 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2274 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002275 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2276
2277 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2278 oat_dex_file->class_offsets_.empty()) {
2279 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002280 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002281
2282 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2283 if (table_size == 0u) {
2284 continue;
2285 }
2286
2287 // Create the lookup table. When `nullptr` is given as the storage buffer,
2288 // TypeLookupTable allocates its own and DexFile takes ownership.
2289 opened_dex_files[i]->CreateTypeLookupTable(/* storage */ nullptr);
2290 TypeLookupTable* table = opened_dex_files[i]->GetTypeLookupTable();
2291
2292 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002293 size_t initial_offset = oat_size_;
2294 size_t rodata_offset = RoundUp(initial_offset, 4);
2295 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002296
2297 if (padding_size != 0u) {
2298 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002299 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002300 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2301 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002302 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002303 return false;
2304 }
2305 }
2306
2307 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002308 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002309 DCHECK_EQ(table_size, table->RawDataLength());
2310
David Brazdil7b49e6c2016-09-01 11:06:18 +01002311 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002312 PLOG(ERROR) << "Failed to write lookup table."
2313 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002314 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002315 return false;
2316 }
2317
2318 oat_dex_file->lookup_table_offset_ = rodata_offset;
2319
David Brazdil7b49e6c2016-09-01 11:06:18 +01002320 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002321 size_oat_lookup_table_ += table_size;
2322 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002323 }
2324
David Brazdil7b49e6c2016-09-01 11:06:18 +01002325 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002326 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002327 << " File: " << oat_rodata->GetLocation();
2328 return false;
2329 }
2330
2331 return true;
2332}
2333
2334bool OatWriter::WriteVdexHeader(OutputStream* vdex_out) {
2335 off_t actual_offset = vdex_out->Seek(0, kSeekSet);
2336 if (actual_offset != 0) {
2337 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2338 << " File: " << vdex_out->GetLocation();
2339 return false;
2340 }
2341
2342 VdexFile::Header vdex_header;
2343 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2344 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345 return false;
2346 }
2347
2348 return true;
2349}
2350
Vladimir Markof4da6752014-08-01 19:04:18 +01002351bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2352 static const uint8_t kPadding[] = {
2353 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2354 };
2355 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002356 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002357 return false;
2358 }
2359 size_code_alignment_ += aligned_code_delta;
2360 return true;
2361}
2362
Vladimir Marko944da602016-02-19 12:27:55 +00002363void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2364 DCHECK(dex_files_ != nullptr);
2365 DCHECK(relative_patcher_ != nullptr);
2366 DCHECK_NE(oat_data_offset_, 0u);
2367 if (image_writer_ != nullptr && !dex_files_->empty()) {
2368 // The oat data begin may not be initialized yet but the oat file offset is ready.
2369 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2370 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2371 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002372 }
2373}
2374
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002375OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2376 DexFileSource source,
2377 CreateTypeLookupTable create_type_lookup_table)
2378 : source_(source),
2379 create_type_lookup_table_(create_type_lookup_table),
2380 dex_file_size_(0),
2381 offset_(0),
2382 dex_file_location_size_(strlen(dex_file_location)),
2383 dex_file_location_data_(dex_file_location),
2384 dex_file_location_checksum_(0u),
2385 dex_file_offset_(0u),
2386 class_offsets_offset_(0u),
2387 lookup_table_offset_(0u),
2388 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002389}
2390
2391size_t OatWriter::OatDexFile::SizeOf() const {
2392 return sizeof(dex_file_location_size_)
2393 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002394 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002395 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002396 + sizeof(class_offsets_offset_)
2397 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002398}
2399
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002400void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2401 DCHECK_EQ(class_offsets_offset_, 0u);
2402 if (!class_offsets_.empty()) {
2403 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002404 size_t initial_offset = oat_writer->oat_size_;
2405 size_t offset = RoundUp(initial_offset, 4);
2406 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002407 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002408 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002409 }
2410}
2411
2412bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2413 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002414 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002415
Vladimir Markoe079e212016-05-25 12:49:49 +01002416 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002417 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002418 return false;
2419 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002420 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002421
Vladimir Markoe079e212016-05-25 12:49:49 +01002422 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002423 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002424 return false;
2425 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002426 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002427
Vladimir Markoe079e212016-05-25 12:49:49 +01002428 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002429 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002430 return false;
2431 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002432 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002433
Vladimir Markoe079e212016-05-25 12:49:49 +01002434 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002435 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002436 return false;
2437 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002438 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002439
Vladimir Markoe079e212016-05-25 12:49:49 +01002440 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002441 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2442 return false;
2443 }
2444 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2445
Vladimir Markoe079e212016-05-25 12:49:49 +01002446 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002447 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2448 return false;
2449 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002450 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002451
2452 return true;
2453}
2454
2455bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002456 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002457 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2458 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002459 return false;
2460 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002461 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002462 return true;
2463}
2464
Brian Carlstromba150c32013-08-27 17:31:03 -07002465OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002466 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002467 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002468 mirror::Class::Status status)
2469 : compiled_methods_(compiled_methods) {
2470 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002471 CHECK_LE(num_non_null_compiled_methods, num_methods);
2472
Brian Carlstrom265091e2013-01-30 14:08:26 -08002473 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002474 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2475
2476 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2477 // apply when there are 0 methods, we just arbitrarily say that 0
2478 // methods means kOatClassNoneCompiled and that we won't use
2479 // kOatClassAllCompiled unless there is at least one compiled
2480 // method. This means in an interpretter only system, we can assert
2481 // that all classes are kOatClassNoneCompiled.
2482 if (num_non_null_compiled_methods == 0) {
2483 type_ = kOatClassNoneCompiled;
2484 } else if (num_non_null_compiled_methods == num_methods) {
2485 type_ = kOatClassAllCompiled;
2486 } else {
2487 type_ = kOatClassSomeCompiled;
2488 }
2489
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002490 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002491 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002492 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002493
2494 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2495 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002496 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002497 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2498 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2499 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2500 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002501 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002502 method_bitmap_size_ = 0;
2503 }
2504
2505 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002506 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002507 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002508 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2509 } else {
2510 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2511 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2512 if (type_ == kOatClassSomeCompiled) {
2513 method_bitmap_->SetBit(i);
2514 }
2515 }
2516 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002517}
2518
Brian Carlstrom265091e2013-01-30 14:08:26 -08002519size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2520 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002521 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2522 if (method_offset == 0) {
2523 return 0;
2524 }
2525 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002526}
2527
2528size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2529 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002530 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002531}
2532
2533size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002534 return sizeof(status_)
2535 + sizeof(type_)
2536 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2537 + method_bitmap_size_
2538 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002539}
2540
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002541bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002542 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002543 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002544 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002545 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002546 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002547 return false;
2548 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002549 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002550
Vladimir Markoe079e212016-05-25 12:49:49 +01002551 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002552 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002553 return false;
2554 }
2555 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002556
Brian Carlstromba150c32013-08-27 17:31:03 -07002557 if (method_bitmap_size_ != 0) {
2558 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002559 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002560 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002561 return false;
2562 }
2563 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002564
Vladimir Markoe079e212016-05-25 12:49:49 +01002565 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002566 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002567 return false;
2568 }
2569 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2570 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002571
Vladimir Markoe079e212016-05-25 12:49:49 +01002572 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002573 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002574 return false;
2575 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002576 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002577 return true;
2578}
2579
Brian Carlstrome24fa612011-09-29 00:53:55 -07002580} // namespace art