blob: f20c715f58b60cb6a1067cbeef86052610333a70 [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"
Vladimir Marko944da602016-02-19 12:27:55 +000042#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000043#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/array.h"
45#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010046#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070047#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010048#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070049#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070050#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070051#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030052#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010053#include "utils/dex_cache_arrays_layout-inl.h"
jeffhaoec014232012-09-05 10:42:25 -070054#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000055#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070056
57namespace art {
58
Vladimir Marko9bdf1082016-01-21 12:15:52 +000059namespace { // anonymous namespace
60
61typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
62
63const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
64 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
65}
66
Vladimir Markoe079e212016-05-25 12:49:49 +010067class ChecksumUpdatingOutputStream : public OutputStream {
68 public:
69 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
70 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
71
72 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
73 oat_header_->UpdateChecksum(buffer, byte_count);
74 return out_->WriteFully(buffer, byte_count);
75 }
76
77 off_t Seek(off_t offset, Whence whence) OVERRIDE {
78 return out_->Seek(offset, whence);
79 }
80
81 bool Flush() OVERRIDE {
82 return out_->Flush();
83 }
84
85 private:
86 OutputStream* const out_;
87 OatHeader* const oat_header_;
88};
89
Vladimir Marko9bdf1082016-01-21 12:15:52 +000090} // anonymous namespace
91
92// Defines the location of the raw dex file to write.
93class OatWriter::DexFileSource {
94 public:
95 explicit DexFileSource(ZipEntry* zip_entry)
96 : type_(kZipEntry), source_(zip_entry) {
97 DCHECK(source_ != nullptr);
98 }
99
100 explicit DexFileSource(File* raw_file)
101 : type_(kRawFile), source_(raw_file) {
102 DCHECK(source_ != nullptr);
103 }
104
105 explicit DexFileSource(const uint8_t* dex_file)
106 : type_(kRawData), source_(dex_file) {
107 DCHECK(source_ != nullptr);
108 }
109
110 bool IsZipEntry() const { return type_ == kZipEntry; }
111 bool IsRawFile() const { return type_ == kRawFile; }
112 bool IsRawData() const { return type_ == kRawData; }
113
114 ZipEntry* GetZipEntry() const {
115 DCHECK(IsZipEntry());
116 DCHECK(source_ != nullptr);
117 return static_cast<ZipEntry*>(const_cast<void*>(source_));
118 }
119
120 File* GetRawFile() const {
121 DCHECK(IsRawFile());
122 DCHECK(source_ != nullptr);
123 return static_cast<File*>(const_cast<void*>(source_));
124 }
125
126 const uint8_t* GetRawData() const {
127 DCHECK(IsRawData());
128 DCHECK(source_ != nullptr);
129 return static_cast<const uint8_t*>(source_);
130 }
131
132 void Clear() {
133 type_ = kNone;
134 source_ = nullptr;
135 }
136
137 private:
138 enum Type {
139 kNone,
140 kZipEntry,
141 kRawFile,
142 kRawData,
143 };
144
145 Type type_;
146 const void* source_;
147};
148
Vladimir Marko49b0f452015-12-10 13:49:19 +0000149class OatWriter::OatClass {
150 public:
151 OatClass(size_t offset,
152 const dchecked_vector<CompiledMethod*>& compiled_methods,
153 uint32_t num_non_null_compiled_methods,
154 mirror::Class::Status status);
155 OatClass(OatClass&& src) = default;
156 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
157 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
158 size_t SizeOf() const;
159 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
160
161 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
162 return compiled_methods_[class_def_method_index];
163 }
164
165 // Offset of start of OatClass from beginning of OatHeader. It is
166 // used to validate file position when writing.
167 size_t offset_;
168
169 // CompiledMethods for each class_def_method_index, or null if no method is available.
170 dchecked_vector<CompiledMethod*> compiled_methods_;
171
172 // Offset from OatClass::offset_ to the OatMethodOffsets for the
173 // class_def_method_index. If 0, it means the corresponding
174 // CompiledMethod entry in OatClass::compiled_methods_ should be
175 // null and that the OatClass::type_ should be kOatClassBitmap.
176 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
177
178 // Data to write.
179
180 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
181 int16_t status_;
182
183 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
184 uint16_t type_;
185
186 uint32_t method_bitmap_size_;
187
188 // bit vector indexed by ClassDef method index. When
189 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
190 // method has an OatMethodOffsets in methods_offsets_, otherwise
191 // the entry was ommited to save space. If OatClassType::type_ is
192 // not is kOatClassBitmap, the bitmap will be null.
193 std::unique_ptr<BitVector> method_bitmap_;
194
195 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
196 // present in the OatClass. Note that some may be missing if
197 // OatClass::compiled_methods_ contains null values (and
198 // oat_method_offsets_offsets_from_oat_class_ should contain 0
199 // values in this case).
200 dchecked_vector<OatMethodOffsets> method_offsets_;
201 dchecked_vector<OatQuickMethodHeader> method_headers_;
202
203 private:
204 size_t GetMethodOffsetsRawSize() const {
205 return method_offsets_.size() * sizeof(method_offsets_[0]);
206 }
207
208 DISALLOW_COPY_AND_ASSIGN(OatClass);
209};
210
211class OatWriter::OatDexFile {
212 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000213 OatDexFile(const char* dex_file_location,
214 DexFileSource source,
215 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000216 OatDexFile(OatDexFile&& src) = default;
217
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000218 const char* GetLocation() const {
219 return dex_file_location_data_;
220 }
221
222 void ReserveTypeLookupTable(OatWriter* oat_writer);
223 void ReserveClassOffsets(OatWriter* oat_writer);
224
Vladimir Marko49b0f452015-12-10 13:49:19 +0000225 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000226 bool Write(OatWriter* oat_writer, OutputStream* out) const;
227 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
228
229 // The source of the dex file.
230 DexFileSource source_;
231
232 // Whether to create the type lookup table.
233 CreateTypeLookupTable create_type_lookup_table_;
234
235 // Dex file size. Initialized when writing the dex file.
236 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000237
238 // Offset of start of OatDexFile from beginning of OatHeader. It is
239 // used to validate file position when writing.
240 size_t offset_;
241
242 // Data to write.
243 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000244 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000245 uint32_t dex_file_location_checksum_;
246 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000247 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000249
250 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000251 dchecked_vector<uint32_t> class_offsets_;
252
253 private:
254 size_t GetClassOffsetsRawSize() const {
255 return class_offsets_.size() * sizeof(class_offsets_[0]);
256 }
257
258 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
259};
260
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100261#define DCHECK_OFFSET() \
262 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
263 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
264
265#define DCHECK_OFFSET_() \
266 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
267 << "file_offset=" << file_offset << " offset_=" << offset_
268
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000269OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
270 : write_state_(WriteState::kAddingDexFileSources),
271 timings_(timings),
272 raw_dex_files_(),
273 zip_archives_(),
274 zipped_dex_files_(),
275 zipped_dex_file_locations_(),
276 compiler_driver_(nullptr),
277 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800278 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000279 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100280 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000281 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100282 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700283 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700284 size_dex_file_alignment_(0),
285 size_executable_offset_alignment_(0),
286 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700287 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700288 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700289 size_interpreter_to_interpreter_bridge_(0),
290 size_interpreter_to_compiled_code_bridge_(0),
291 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800292 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700293 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700294 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700295 size_quick_to_interpreter_bridge_(0),
296 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100297 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700298 size_code_(0),
299 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100300 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100301 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700302 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700303 size_oat_dex_file_location_size_(0),
304 size_oat_dex_file_location_data_(0),
305 size_oat_dex_file_location_checksum_(0),
306 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000307 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000308 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000309 size_oat_lookup_table_alignment_(0),
310 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000311 size_oat_class_offsets_alignment_(0),
312 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700313 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700314 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700315 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100316 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000317 relative_patcher_(nullptr),
318 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000319}
320
321bool OatWriter::AddDexFileSource(const char* filename,
322 const char* location,
323 CreateTypeLookupTable create_type_lookup_table) {
324 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
325 uint32_t magic;
326 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700327 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
328 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000329 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
330 return false;
331 } else if (IsDexMagic(magic)) {
332 // The file is open for reading, not writing, so it's OK to let the File destructor
333 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700334 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000335 oat_dex_files_.emplace_back(location,
336 DexFileSource(raw_dex_files_.back().get()),
337 create_type_lookup_table);
338 } else if (IsZipMagic(magic)) {
339 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
340 return false;
341 }
342 } else {
343 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
344 return false;
345 }
346 return true;
347}
348
349// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700350bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000351 const char* location,
352 CreateTypeLookupTable create_type_lookup_table) {
353 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
354 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700355 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000356 ZipArchive* zip_archive = zip_archives_.back().get();
357 if (zip_archive == nullptr) {
358 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
359 << error_msg;
360 return false;
361 }
362 for (size_t i = 0; ; ++i) {
363 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
364 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
365 if (entry == nullptr) {
366 break;
367 }
368 zipped_dex_files_.push_back(std::move(entry));
369 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
370 const char* full_location = zipped_dex_file_locations_.back().c_str();
371 oat_dex_files_.emplace_back(full_location,
372 DexFileSource(zipped_dex_files_.back().get()),
373 create_type_lookup_table);
374 }
375 if (zipped_dex_file_locations_.empty()) {
376 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
377 return false;
378 }
379 return true;
380}
381
382// Add dex file source from raw memory.
383bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
384 const char* location,
385 uint32_t location_checksum,
386 CreateTypeLookupTable create_type_lookup_table) {
387 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
388 if (data.size() < sizeof(DexFile::Header)) {
389 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
390 << data.size() << " File: " << location;
391 return false;
392 }
393 if (!ValidateDexFileHeader(data.data(), location)) {
394 return false;
395 }
396 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
397 if (data.size() < header->file_size_) {
398 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
399 << " file size from header: " << header->file_size_ << " File: " << location;
400 return false;
401 }
402
403 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
404 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
405 return true;
406}
407
408dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
409 dchecked_vector<const char*> locations;
410 locations.reserve(oat_dex_files_.size());
411 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
412 locations.push_back(oat_dex_file.GetLocation());
413 }
414 return locations;
415}
416
417bool OatWriter::WriteAndOpenDexFiles(
418 OutputStream* rodata,
419 File* file,
420 InstructionSet instruction_set,
421 const InstructionSetFeatures* instruction_set_features,
422 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800423 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000424 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
425 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
426 CHECK(write_state_ == WriteState::kAddingDexFileSources);
427
428 size_t offset = InitOatHeader(instruction_set,
429 instruction_set_features,
430 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
431 key_value_store);
432 offset = InitOatDexFiles(offset);
433 size_ = offset;
434
435 std::unique_ptr<MemMap> dex_files_map;
436 std::vector<std::unique_ptr<const DexFile>> dex_files;
437 if (!WriteDexFiles(rodata, file)) {
438 return false;
439 }
440 // Reserve space for type lookup tables and update type_lookup_table_offset_.
441 for (OatDexFile& oat_dex_file : oat_dex_files_) {
442 oat_dex_file.ReserveTypeLookupTable(this);
443 }
444 size_t size_after_type_lookup_tables = size_;
445 // Reserve space for class offsets and update class_offsets_offset_.
446 for (OatDexFile& oat_dex_file : oat_dex_files_) {
447 oat_dex_file.ReserveClassOffsets(this);
448 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100449 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
450 if (!WriteOatDexFiles(&checksum_updating_rodata) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000451 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800452 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000453 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
454 return false;
455 }
456
Vladimir Markoe079e212016-05-25 12:49:49 +0100457 // Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
458 // piece would be difficult because we're not using the OutpuStream directly.
459 if (!oat_dex_files_.empty()) {
460 size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
461 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
462 }
463
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000464 *opened_dex_files_map = std::move(dex_files_map);
465 *opened_dex_files = std::move(dex_files);
466 write_state_ = WriteState::kPrepareLayout;
467 return true;
468}
469
470void OatWriter::PrepareLayout(const CompilerDriver* compiler,
471 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000472 const std::vector<const DexFile*>& dex_files,
473 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000474 CHECK(write_state_ == WriteState::kPrepareLayout);
475
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000476 compiler_driver_ = compiler;
477 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000478 dex_files_ = &dex_files;
479 relative_patcher_ = relative_patcher;
480 SetMultiOatRelativePatcherAdjustment();
481
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000482 if (compiling_boot_image_) {
483 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800484 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100485 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000486 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100487
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800489 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800491 offset = InitOatClasses(offset);
492 }
493 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000494 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100495 offset = InitOatMaps(offset);
496 }
497 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000498 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800499 offset = InitOatCode(offset);
500 }
501 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000502 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800503 offset = InitOatCodeDexFiles(offset);
504 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700505 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700506
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800507 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100508 // Allocate space for app dex cache arrays in the .bss section.
509 size_t bss_start = RoundUp(size_, kPageSize);
Andreas Gampe542451c2016-07-26 09:02:02 -0700510 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100511 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000512 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100513 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
514 DexCacheArraysLayout layout(pointer_size, dex_file);
515 bss_size_ += layout.Size();
516 }
517 }
518
Brian Carlstrome24fa612011-09-29 00:53:55 -0700519 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800520 if (compiling_boot_image_) {
521 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000522 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800523 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524
525 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700526}
527
Ian Rogers0571d352011-11-03 19:51:38 -0700528OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700529}
530
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100531class OatWriter::DexMethodVisitor {
532 public:
533 DexMethodVisitor(OatWriter* writer, size_t offset)
534 : writer_(writer),
535 offset_(offset),
536 dex_file_(nullptr),
537 class_def_index_(DexFile::kDexNoIndex) {
538 }
539
540 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
541 DCHECK(dex_file_ == nullptr);
542 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
543 dex_file_ = dex_file;
544 class_def_index_ = class_def_index;
545 return true;
546 }
547
548 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
549
550 virtual bool EndClass() {
551 if (kIsDebugBuild) {
552 dex_file_ = nullptr;
553 class_def_index_ = DexFile::kDexNoIndex;
554 }
555 return true;
556 }
557
558 size_t GetOffset() const {
559 return offset_;
560 }
561
562 protected:
563 virtual ~DexMethodVisitor() { }
564
565 OatWriter* const writer_;
566
567 // The offset is usually advanced for each visited method by the derived class.
568 size_t offset_;
569
570 // The dex file and class def index are set in StartClass().
571 const DexFile* dex_file_;
572 size_t class_def_index_;
573};
574
575class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
576 public:
577 OatDexMethodVisitor(OatWriter* writer, size_t offset)
578 : DexMethodVisitor(writer, offset),
579 oat_class_index_(0u),
580 method_offsets_index_(0u) {
581 }
582
583 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
584 DexMethodVisitor::StartClass(dex_file, class_def_index);
585 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
586 method_offsets_index_ = 0u;
587 return true;
588 }
589
590 bool EndClass() {
591 ++oat_class_index_;
592 return DexMethodVisitor::EndClass();
593 }
594
595 protected:
596 size_t oat_class_index_;
597 size_t method_offsets_index_;
598};
599
600class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
601 public:
602 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
603 : DexMethodVisitor(writer, offset),
604 compiled_methods_(),
605 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000606 size_t num_classes = 0u;
607 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
608 num_classes += oat_dex_file.class_offsets_.size();
609 }
610 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100611 compiled_methods_.reserve(256u);
612 }
613
614 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
615 DexMethodVisitor::StartClass(dex_file, class_def_index);
616 compiled_methods_.clear();
617 num_non_null_compiled_methods_ = 0u;
618 return true;
619 }
620
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300621 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
622 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100623 // Fill in the compiled_methods_ array for methods that have a
624 // CompiledMethod. We track the number of non-null entries in
625 // num_non_null_compiled_methods_ since we only want to allocate
626 // OatMethodOffsets for the compiled methods.
627 uint32_t method_idx = it.GetMemberIndex();
628 CompiledMethod* compiled_method =
629 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
630 compiled_methods_.push_back(compiled_method);
631 if (compiled_method != nullptr) {
632 ++num_non_null_compiled_methods_;
633 }
634 return true;
635 }
636
637 bool EndClass() {
638 ClassReference class_ref(dex_file_, class_def_index_);
639 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
640 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700641 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100642 status = compiled_class->GetStatus();
643 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
644 status = mirror::Class::kStatusError;
645 } else {
646 status = mirror::Class::kStatusNotReady;
647 }
648
Vladimir Marko49b0f452015-12-10 13:49:19 +0000649 writer_->oat_classes_.emplace_back(offset_,
650 compiled_methods_,
651 num_non_null_compiled_methods_,
652 status);
653 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100654 return DexMethodVisitor::EndClass();
655 }
656
657 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000658 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100659 size_t num_non_null_compiled_methods_;
660};
661
662class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
663 public:
664 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100665 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100666 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100667 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100668 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
669 }
670
671 bool EndClass() {
672 OatDexMethodVisitor::EndClass();
673 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100674 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100675 }
676 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100677 }
678
679 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700680 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000681 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100682 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
683
684 if (compiled_method != nullptr) {
685 // Derived from CompiledMethod.
686 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687
Vladimir Marko35831e82015-09-11 11:59:18 +0100688 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
689 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800690 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800691
David Srbecky009e2a62015-04-15 02:46:30 +0100692 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100693 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800694 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000695 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000696 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
697 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800698 // Duplicate methods, we want the same code for both of them so that the oat writer puts
699 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800700 } else {
701 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100702 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800703 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000704 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100705 quick_code_offset = dedupe_map_.GetOrCreate(
706 compiled_method,
707 [this, &deduped, compiled_method, &it, thumb_offset]() {
708 deduped = false;
709 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
710 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800711 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100712
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100713 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000714 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100715 // TODO: Should this be a hard failure?
716 LOG(WARNING) << "Multiple definitions of "
717 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000718 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
719 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100720 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000721 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100722 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800723 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100724
Elliott Hughes956af0f2014-12-11 14:34:28 -0800725 // Update quick method header.
726 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
727 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800728 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100729 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
730 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100731 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800732 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
733 // to 0-offset and we need to adjust it by code_offset.
734 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100735 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800736 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100737 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800738 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800739 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
740 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
741 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100742 *method_header = OatQuickMethodHeader(vmap_table_offset,
743 frame_size_in_bytes,
744 core_spill_mask,
745 fp_spill_mask,
746 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100747
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000748 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800749 // Update offsets. (Checksum is updated when writing.)
750 offset_ += sizeof(*method_header); // Method header is prepended before code.
751 offset_ += code_size;
752 // Record absolute patch locations.
753 if (!compiled_method->GetPatches().empty()) {
754 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
755 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000756 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100757 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100758 }
759 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100760 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800761 }
Alex Light78382fa2014-06-06 15:45:32 -0700762
David Srbecky91cc06c2016-03-07 16:13:58 +0000763 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000764 // Exclude quickened dex methods (code_size == 0) since they have no native code.
765 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
766 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800767 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000768 debug::MethodDebugInfo info = debug::MethodDebugInfo();
769 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000770 info.dex_file = dex_file_;
771 info.class_def_index = class_def_index_;
772 info.dex_method_index = it.GetMemberIndex();
773 info.access_flags = it.GetMethodAccessFlags();
774 info.code_item = it.GetMethodCodeItem();
775 info.isa = compiled_method->GetInstructionSet();
776 info.deduped = deduped;
777 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
778 info.is_optimized = method_header->IsOptimized();
779 info.is_code_address_text_relative = true;
780 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
781 info.code_size = code_size;
782 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
783 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
784 info.cfi = compiled_method->GetCFIInfo();
785 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100786 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100787
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100788 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
789 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
790 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100791 ++method_offsets_index_;
792 }
793
794 return true;
795 }
796
797 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000798 struct CodeOffsetsKeyComparator {
799 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100800 // Code is deduplicated by CompilerDriver, compare only data pointers.
801 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
802 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000803 }
804 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100805 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
806 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000807 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100808 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
809 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000810 }
811 return false;
812 }
813 };
814
David Srbecky009e2a62015-04-15 02:46:30 +0100815 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
816 const ClassDataItemIterator& it,
817 uint32_t thumb_offset) {
818 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100819 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100820 offset_ = compiled_method->AlignCode(offset_);
821 DCHECK_ALIGNED_PARAM(offset_,
822 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
823 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
824 }
825
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100826 // Deduplication is already done on a pointer basis by the compiler driver,
827 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100828 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100829
David Srbecky009e2a62015-04-15 02:46:30 +0100830 // Cache of compiler's --debuggable option.
831 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832};
833
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100834class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
835 public:
836 InitMapMethodVisitor(OatWriter* writer, size_t offset)
837 : OatDexMethodVisitor(writer, offset) {
838 }
839
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700840 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700841 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000842 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100843 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
844
845 if (compiled_method != nullptr) {
846 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100847 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100848
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100849 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100850 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100851 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100852 size_t offset = dedupe_map_.GetOrCreate(
853 map.data(),
854 [this, map_size]() {
855 uint32_t new_offset = offset_;
856 offset_ += map_size;
857 return new_offset;
858 });
859 // Code offset is not initialized yet, so set the map offset to 0u-offset.
860 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
861 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100862 }
863 ++method_offsets_index_;
864 }
865
866 return true;
867 }
868
869 private:
870 // Deduplication is already done on a pointer basis by the compiler driver,
871 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100872 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100873};
874
875class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
876 public:
877 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800878 : OatDexMethodVisitor(writer, offset),
879 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100880 }
881
882 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700883 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800884 const DexFile::TypeId& type_id =
885 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
886 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
887 // Skip methods that are not in the image.
888 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
889 return true;
890 }
891
Vladimir Marko49b0f452015-12-10 13:49:19 +0000892 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100893 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
894
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800895 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100896 if (compiled_method != nullptr) {
897 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
898 offsets = oat_class->method_offsets_[method_offsets_index_];
899 ++method_offsets_index_;
900 }
901
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100902 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 // Unchecked as we hold mutator_lock_ on entry.
904 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800905 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700906 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
907 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800908 ArtMethod* method;
909 if (writer_->HasBootImage()) {
910 const InvokeType invoke_type = it.GetMethodInvokeType(
911 dex_file_->GetClassDef(class_def_index_));
912 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
913 *dex_file_,
914 it.GetMemberIndex(),
915 dex_cache,
916 ScopedNullHandle<mirror::ClassLoader>(),
917 nullptr,
918 invoke_type);
919 if (method == nullptr) {
920 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
921 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
922 soa.Self()->AssertPendingException();
923 mirror::Throwable* exc = soa.Self()->GetException();
924 std::string dump = exc->Dump();
925 LOG(FATAL) << dump;
926 UNREACHABLE();
927 }
928 } else {
929 // Should already have been resolved by the compiler, just peek into the dex cache.
930 // It may not be resolved if the class failed to verify, in this case, don't set the
931 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
932 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700933 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800934 if (method != nullptr &&
935 compiled_method != nullptr &&
936 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100937 method->SetEntryPointFromQuickCompiledCodePtrSize(
938 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
939 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100940
941 return true;
942 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800943
944 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -0700945 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946};
947
948class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
949 public:
950 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100951 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952 : OatDexMethodVisitor(writer, relative_offset),
953 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100954 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100955 soa_(Thread::Current()),
956 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100957 class_linker_(Runtime::Current()->GetClassLinker()),
958 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100959 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800960 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100961 // If we're creating the image, the address space must be ready so that we can apply patches.
962 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100963 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100964 }
965
Vladimir Markof4da6752014-08-01 19:04:18 +0100966 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100967 }
968
969 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700970 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100971 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
972 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700973 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000974 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100975 }
976 return true;
977 }
978
Mathieu Chartier90443472015-07-16 20:32:27 -0700979 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100980 bool result = OatDexMethodVisitor::EndClass();
981 if (oat_class_index_ == writer_->oat_classes_.size()) {
982 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000983 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100984 if (UNLIKELY(offset_ == 0u)) {
985 PLOG(ERROR) << "Failed to write final relative call thunks";
986 result = false;
987 }
988 }
989 return result;
990 }
991
992 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700993 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000994 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100995 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
996
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700997 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
998 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700999 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001000 size_t file_offset = file_offset_;
1001 OutputStream* out = out_;
1002
Vladimir Marko35831e82015-09-11 11:59:18 +01001003 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1004 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001005
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001006 // Deduplicate code arrays.
1007 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1008 if (method_offsets.code_offset_ > offset_) {
1009 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1010 if (offset_ == 0u) {
1011 ReportWriteFailure("relative call thunk", it);
1012 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001013 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001014 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1015 uint32_t aligned_code_delta = aligned_offset - offset_;
1016 if (aligned_code_delta != 0) {
1017 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1018 ReportWriteFailure("code alignment padding", it);
1019 return false;
1020 }
1021 offset_ += aligned_code_delta;
1022 DCHECK_OFFSET_();
1023 }
1024 DCHECK_ALIGNED_PARAM(offset_,
1025 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1026 DCHECK_EQ(method_offsets.code_offset_,
1027 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1028 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1029 const OatQuickMethodHeader& method_header =
1030 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001031 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001032 ReportWriteFailure("method header", it);
1033 return false;
1034 }
1035 writer_->size_method_header_ += sizeof(method_header);
1036 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001037 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001038
1039 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001040 patched_code_.assign(quick_code.begin(), quick_code.end());
1041 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001042 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001043 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001044 switch (patch.GetType()) {
1045 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001046 // NOTE: Relative calls across oat files are not supported.
1047 uint32_t target_offset = GetTargetOffset(patch);
1048 writer_->relative_patcher_->PatchCall(&patched_code_,
1049 literal_offset,
1050 offset_ + literal_offset,
1051 target_offset);
1052 break;
1053 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001054 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001055 uint32_t target_offset = GetDexCacheOffset(patch);
1056 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1057 patch,
1058 offset_ + literal_offset,
1059 target_offset);
1060 break;
1061 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001062 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001063 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1064 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1065 patch,
1066 offset_ + literal_offset,
1067 target_offset);
1068 break;
1069 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001070 case LinkerPatch::Type::kTypeRelative: {
1071 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1072 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1073 patch,
1074 offset_ + literal_offset,
1075 target_offset);
1076 break;
1077 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001078 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001079 uint32_t target_offset = GetTargetOffset(patch);
1080 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1081 break;
1082 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001083 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001084 ArtMethod* method = GetTargetMethod(patch);
1085 PatchMethodAddress(&patched_code_, literal_offset, method);
1086 break;
1087 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001088 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001089 mirror::String* string = GetTargetString(patch);
1090 PatchObjectAddress(&patched_code_, literal_offset, string);
1091 break;
1092 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001093 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001094 mirror::Class* type = GetTargetType(patch);
1095 PatchObjectAddress(&patched_code_, literal_offset, type);
1096 break;
1097 }
1098 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001099 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001100 break;
1101 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001102 }
1103 }
1104 }
1105
Vladimir Markoe079e212016-05-25 12:49:49 +01001106 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001107 ReportWriteFailure("method code", it);
1108 return false;
1109 }
1110 writer_->size_code_ += code_size;
1111 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001112 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001113 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001114 ++method_offsets_index_;
1115 }
1116
1117 return true;
1118 }
1119
1120 private:
1121 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001122 const size_t file_offset_;
1123 const ScopedObjectAccess soa_;
1124 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001125 ClassLinker* const class_linker_;
1126 mirror::DexCache* dex_cache_;
1127 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001128
1129 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1130 PLOG(ERROR) << "Failed to write " << what << " for "
1131 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1132 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001133
Mathieu Chartiere401d142015-04-22 13:56:20 -07001134 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001135 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001136 MethodReference ref = patch.TargetMethod();
1137 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001138 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1139 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001140 ArtMethod* method = dex_cache->GetResolvedMethod(
1141 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001142 CHECK(method != nullptr);
1143 return method;
1144 }
1145
Mathieu Chartier90443472015-07-16 20:32:27 -07001146 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001147 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1148 // If there's no new compiled code, either we're compiling an app and the target method
1149 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001150 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001151 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001152 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001153 PointerSize size =
1154 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001155 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1156 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001157 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001158 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1159 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1160 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1161 target_offset = PointerToLowMemUInt32(oat_code_offset);
1162 } else {
1163 target_offset = target->IsNative()
1164 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1165 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1166 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001167 }
1168 return target_offset;
1169 }
1170
Vladimir Marko052164a2016-04-27 13:54:18 +01001171 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
1172 SHARED_REQUIRES(Locks::mutator_lock_) {
1173 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001174 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001175 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1176 }
1177
1178 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1179 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001180 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1181 CHECK(type != nullptr);
1182 return type;
1183 }
1184
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001185 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001186 mirror::DexCache* dex_cache = GetDexCache(patch.TargetStringDexFile());
1187 mirror::String* string = dex_cache->GetResolvedString(patch.TargetStringIndex());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001188 DCHECK(string != nullptr);
1189 DCHECK(writer_->HasBootImage() ||
1190 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1191 return string;
1192 }
1193
Mathieu Chartier90443472015-07-16 20:32:27 -07001194 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001195 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001196 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1197 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1198 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1199 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001200 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001201 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001202 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1203 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001204 }
1205 }
1206
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001207 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1208 DCHECK(writer_->HasBootImage());
1209 object = writer_->image_writer_->GetImageAddress(object);
1210 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1211 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1212 // TODO: Clean up offset types. The target offset must be treated as signed.
1213 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1214 }
1215
Vladimir Markof4da6752014-08-01 19:04:18 +01001216 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001217 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001218 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001219 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001220 } else {
1221 // NOTE: We're using linker patches for app->boot references when the image can
1222 // be relocated and therefore we need to emit .oat_patches. We're not using this
1223 // for app->app references, so check that the object is in the image space.
1224 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001225 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001226 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001227 uint32_t address = PointerToLowMemUInt32(object);
1228 DCHECK_LE(offset + 4, code->size());
1229 uint8_t* data = &(*code)[offset];
1230 data[0] = address & 0xffu;
1231 data[1] = (address >> 8) & 0xffu;
1232 data[2] = (address >> 16) & 0xffu;
1233 data[3] = (address >> 24) & 0xffu;
1234 }
1235
Mathieu Chartiere401d142015-04-22 13:56:20 -07001236 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001237 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001238 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001239 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001240 } else if (kIsDebugBuild) {
1241 // NOTE: We're using linker patches for app->boot references when the image can
1242 // be relocated and therefore we need to emit .oat_patches. We're not using this
1243 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001244 std::vector<gc::space::ImageSpace*> image_spaces =
1245 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1246 bool contains_method = false;
1247 for (gc::space::ImageSpace* image_space : image_spaces) {
1248 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1249 contains_method |=
1250 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1251 }
1252 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001253 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001254 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001255 uint32_t address = PointerToLowMemUInt32(method);
1256 DCHECK_LE(offset + 4, code->size());
1257 uint8_t* data = &(*code)[offset];
1258 data[0] = address & 0xffu;
1259 data[1] = (address >> 8) & 0xffu;
1260 data[2] = (address >> 16) & 0xffu;
1261 data[3] = (address >> 24) & 0xffu;
1262 }
1263
Vladimir Markof4da6752014-08-01 19:04:18 +01001264 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001265 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001266 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001267 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001268 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1269 // TODO: Clean up offset types.
1270 // The target_offset must be treated as signed for cross-oat patching.
1271 const void* target = reinterpret_cast<const void*>(
1272 writer_->image_writer_->GetOatDataBegin(oat_index) +
1273 static_cast<int32_t>(target_offset));
1274 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001275 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001276 DCHECK_LE(offset + 4, code->size());
1277 uint8_t* data = &(*code)[offset];
1278 data[0] = address & 0xffu;
1279 data[1] = (address >> 8) & 0xffu;
1280 data[2] = (address >> 16) & 0xffu;
1281 data[3] = (address >> 24) & 0xffu;
1282 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001283};
1284
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001285class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1286 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001287 WriteMapMethodVisitor(OatWriter* writer,
1288 OutputStream* out,
1289 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001290 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001291 : OatDexMethodVisitor(writer, relative_offset),
1292 out_(out),
1293 file_offset_(file_offset) {
1294 }
1295
1296 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001297 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001298 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1299
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001300 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001301 size_t file_offset = file_offset_;
1302 OutputStream* out = out_;
1303
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001304 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1305 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001306 ++method_offsets_index_;
1307
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001308 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1309 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1310 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1311 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1312
1313 if (map_offset != 0u) {
1314 // Transform map_offset to actual oat data offset.
1315 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1316 DCHECK_NE(map_offset, 0u);
1317 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1318
1319 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1320 size_t map_size = map.size() * sizeof(map[0]);
1321 if (map_offset == offset_) {
1322 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001323 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001324 ReportWriteFailure(it);
1325 return false;
1326 }
1327 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001328 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001329 }
1330 DCHECK_OFFSET_();
1331 }
1332
1333 return true;
1334 }
1335
1336 private:
1337 OutputStream* const out_;
1338 size_t const file_offset_;
1339
1340 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001341 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001342 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1343 }
1344};
1345
1346// Visit all methods from all classes in all dex files with the specified visitor.
1347bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1348 for (const DexFile* dex_file : *dex_files_) {
1349 const size_t class_def_count = dex_file->NumClassDefs();
1350 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1351 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1352 return false;
1353 }
1354 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001355 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001356 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001357 ClassDataItemIterator it(*dex_file, class_data);
1358 while (it.HasNextStaticField()) {
1359 it.Next();
1360 }
1361 while (it.HasNextInstanceField()) {
1362 it.Next();
1363 }
1364 size_t class_def_method_index = 0u;
1365 while (it.HasNextDirectMethod()) {
1366 if (!visitor->VisitMethod(class_def_method_index, it)) {
1367 return false;
1368 }
1369 ++class_def_method_index;
1370 it.Next();
1371 }
1372 while (it.HasNextVirtualMethod()) {
1373 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1374 return false;
1375 }
1376 ++class_def_method_index;
1377 it.Next();
1378 }
1379 }
1380 if (UNLIKELY(!visitor->EndClass())) {
1381 return false;
1382 }
1383 }
1384 }
1385 return true;
1386}
1387
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001388size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1389 const InstructionSetFeatures* instruction_set_features,
1390 uint32_t num_dex_files,
1391 SafeMap<std::string, std::string>* key_value_store) {
1392 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1393 oat_header_.reset(OatHeader::Create(instruction_set,
1394 instruction_set_features,
1395 num_dex_files,
1396 key_value_store));
1397 size_oat_header_ += sizeof(OatHeader);
1398 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001399 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001400}
1401
1402size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001403 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1404 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001405 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001406 oat_dex_file.offset_ = offset;
1407 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001408 }
1409 return offset;
1410}
1411
Brian Carlstrom389efb02012-01-11 12:06:26 -08001412size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001413 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001414 InitOatClassesMethodVisitor visitor(this, offset);
1415 bool success = VisitDexMethods(&visitor);
1416 CHECK(success);
1417 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001418
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001419 // Update oat_dex_files_.
1420 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001421 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1422 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001424 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001425 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001426 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001427 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001428 CHECK(oat_class_it == oat_classes_.end());
1429
1430 return offset;
1431}
1432
1433size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001434 InitMapMethodVisitor visitor(this, offset);
1435 bool success = VisitDexMethods(&visitor);
1436 DCHECK(success);
1437 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001438
Brian Carlstrome24fa612011-09-29 00:53:55 -07001439 return offset;
1440}
1441
1442size_t OatWriter::InitOatCode(size_t offset) {
1443 // calculate the offsets within OatHeader to executable code
1444 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001445 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001446 // required to be on a new page boundary
1447 offset = RoundUp(offset, kPageSize);
1448 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001449 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001450 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001451 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001452
Ian Rogers848871b2013-08-05 10:56:33 -07001453 #define DO_TRAMPOLINE(field, fn_name) \
1454 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001455 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1456 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001457 (field) = compiler_driver_->Create ## fn_name(); \
1458 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001459
Ian Rogers848871b2013-08-05 10:56:33 -07001460 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001461 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001462 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001463 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1464 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465
Ian Rogers848871b2013-08-05 10:56:33 -07001466 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001467 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001468 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1469 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1470 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001471 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001472 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001473 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001474 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001475 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001476 return offset;
1477}
1478
1479size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001480 #define VISIT(VisitorType) \
1481 do { \
1482 VisitorType visitor(this, offset); \
1483 bool success = VisitDexMethods(&visitor); \
1484 DCHECK(success); \
1485 offset = visitor.GetOffset(); \
1486 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001487
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001488 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001489 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001490 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001491 }
Logan Chien8b977d32012-02-21 19:14:55 +08001492
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001493 #undef VISIT
1494
Brian Carlstrome24fa612011-09-29 00:53:55 -07001495 return offset;
1496}
1497
David Srbeckybc90fd02015-04-22 19:40:27 +01001498bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001499 CHECK(write_state_ == WriteState::kWriteRoData);
1500
Vladimir Markoe079e212016-05-25 12:49:49 +01001501 // Wrap out to update checksum with each write.
1502 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1503 out = &checksum_updating_out;
1504
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001505 if (!WriteClassOffsets(out)) {
1506 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001507 return false;
1508 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001509
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001510 if (!WriteClasses(out)) {
1511 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001512 return false;
1513 }
1514
Vladimir Markof4da6752014-08-01 19:04:18 +01001515 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001516 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001517 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1518 return false;
1519 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001520 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001521 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001522 relative_offset = WriteMaps(out, file_offset, relative_offset);
1523 if (relative_offset == 0) {
1524 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1525 return false;
1526 }
1527
David Srbeckybc90fd02015-04-22 19:40:27 +01001528 // Write padding.
1529 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1530 relative_offset += size_executable_offset_alignment_;
1531 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1532 size_t expected_file_offset = file_offset + relative_offset;
1533 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1534 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1535 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1536 return 0;
1537 }
1538 DCHECK_OFFSET();
1539
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001540 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001541 return true;
1542}
1543
1544bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001545 CHECK(write_state_ == WriteState::kWriteText);
1546
Vladimir Markoe079e212016-05-25 12:49:49 +01001547 // Wrap out to update checksum with each write.
1548 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1549 out = &checksum_updating_out;
1550
Vladimir Marko944da602016-02-19 12:27:55 +00001551 SetMultiOatRelativePatcherAdjustment();
1552
David Srbeckybc90fd02015-04-22 19:40:27 +01001553 const size_t file_offset = oat_data_offset_;
1554 size_t relative_offset = oat_header_->GetExecutableOffset();
1555 DCHECK_OFFSET();
1556
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001557 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001558 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001559 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001560 return false;
1561 }
1562
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001563 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1564 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001565 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001566 return false;
1567 }
1568
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001570 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001571 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1572 return false;
1573 }
1574
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001575 if (kIsDebugBuild) {
1576 uint32_t size_total = 0;
1577 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001578 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1579 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001580
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001581 DO_STAT(size_dex_file_alignment_);
1582 DO_STAT(size_executable_offset_alignment_);
1583 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001584 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001585 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001586 DO_STAT(size_interpreter_to_interpreter_bridge_);
1587 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1588 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001589 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001590 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001591 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001592 DO_STAT(size_quick_to_interpreter_bridge_);
1593 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001594 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001595 DO_STAT(size_code_);
1596 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001597 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001598 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001599 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001600 DO_STAT(size_oat_dex_file_location_size_);
1601 DO_STAT(size_oat_dex_file_location_data_);
1602 DO_STAT(size_oat_dex_file_location_checksum_);
1603 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001604 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001605 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001606 DO_STAT(size_oat_lookup_table_alignment_);
1607 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001608 DO_STAT(size_oat_class_offsets_alignment_);
1609 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001610 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001611 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001612 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001613 DO_STAT(size_oat_class_method_offsets_);
1614 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001615
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001616 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001617 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001618 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001619 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001620
Vladimir Markof4da6752014-08-01 19:04:18 +01001621 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001622 CHECK_EQ(size_, relative_offset);
1623
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001624 write_state_ = WriteState::kWriteHeader;
1625 return true;
1626}
1627
1628bool OatWriter::WriteHeader(OutputStream* out,
1629 uint32_t image_file_location_oat_checksum,
1630 uintptr_t image_file_location_oat_begin,
1631 int32_t image_patch_delta) {
1632 CHECK(write_state_ == WriteState::kWriteHeader);
1633
1634 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1635 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1636 if (compiler_driver_->IsBootImage()) {
1637 CHECK_EQ(image_patch_delta, 0);
1638 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1639 } else {
1640 CHECK_ALIGNED(image_patch_delta, kPageSize);
1641 oat_header_->SetImagePatchDelta(image_patch_delta);
1642 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001643 oat_header_->UpdateChecksumWithHeaderData();
1644
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001645 const size_t file_offset = oat_data_offset_;
1646
1647 off_t current_offset = out->Seek(0, kSeekCurrent);
1648 if (current_offset == static_cast<off_t>(-1)) {
1649 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1650 return false;
1651 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001652 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001653 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1654 return false;
1655 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001656 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001657
1658 // Flush all other data before writing the header.
1659 if (!out->Flush()) {
1660 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1661 return false;
1662 }
1663 // Write the header.
1664 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001665 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001666 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1667 return false;
1668 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001669 // Flush the header data.
1670 if (!out->Flush()) {
1671 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001672 return false;
1673 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001674
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001675 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1676 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1677 return false;
1678 }
1679 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1680
1681 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001682 return true;
1683}
1684
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685bool OatWriter::WriteClassOffsets(OutputStream* out) {
1686 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1687 if (oat_dex_file.class_offsets_offset_ != 0u) {
1688 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1689 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1690 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1691 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1692 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001693 return false;
1694 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001695 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1696 return false;
1697 }
1698 }
1699 }
1700 return true;
1701}
1702
1703bool OatWriter::WriteClasses(OutputStream* out) {
1704 for (OatClass& oat_class : oat_classes_) {
1705 if (!oat_class.Write(this, out, oat_data_offset_)) {
1706 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1707 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001708 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001709 }
1710 return true;
1711}
1712
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001713size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001714 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001715 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1716 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1717 return 0;
1718 }
1719 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001720 size_vmap_table_ = relative_offset - vmap_tables_offset;
1721
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001722 return relative_offset;
1723}
1724
1725size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001726 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001727 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001728
Ian Rogers848871b2013-08-05 10:56:33 -07001729 #define DO_TRAMPOLINE(field) \
1730 do { \
1731 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1732 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001733 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001734 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001735 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001736 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001737 return false; \
1738 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001739 size_ ## field += (field)->size(); \
1740 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001741 DCHECK_OFFSET(); \
1742 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001743
Ian Rogers848871b2013-08-05 10:56:33 -07001744 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001745 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001746 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001747 DO_TRAMPOLINE(quick_resolution_trampoline_);
1748 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1749 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001750 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001751 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001752}
1753
Ian Rogers3d504072014-03-01 09:16:49 -08001754size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001755 const size_t file_offset,
1756 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001757 #define VISIT(VisitorType) \
1758 do { \
1759 VisitorType visitor(this, out, file_offset, relative_offset); \
1760 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1761 return 0; \
1762 } \
1763 relative_offset = visitor.GetOffset(); \
1764 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001765
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001766 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001767
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001768 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001769
Vladimir Markob163bb72015-03-31 21:49:49 +01001770 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1771 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1772 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1773
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001774 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001775}
1776
Vladimir Marko944da602016-02-19 12:27:55 +00001777bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001778 // Get the elf file offset of the oat file.
1779 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1780 if (raw_file_offset == static_cast<off_t>(-1)) {
1781 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1782 return false;
1783 }
1784 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1785 return true;
1786}
1787
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001788bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1789 // Read the dex file header and perform minimal verification.
1790 uint8_t raw_header[sizeof(DexFile::Header)];
1791 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1792 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1793 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1794 return false;
1795 }
1796 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1797 return false;
1798 }
1799
1800 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1801 oat_dex_file->dex_file_size_ = header->file_size_;
1802 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1803 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1804 return true;
1805}
1806
1807bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1808 if (!DexFile::IsMagicValid(raw_header)) {
1809 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1810 return false;
1811 }
1812 if (!DexFile::IsVersionValid(raw_header)) {
1813 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1814 return false;
1815 }
1816 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1817 if (header->file_size_ < sizeof(DexFile::Header)) {
1818 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1819 << " File: " << location;
1820 return false;
1821 }
1822 return true;
1823}
1824
1825bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1826 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1827
1828 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001829 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001830 return false;
1831 }
1832
1833 // Write dex files.
1834 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1835 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1836 return false;
1837 }
1838 }
1839
1840 // Close sources.
1841 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1842 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1843 }
1844 zipped_dex_files_.clear();
1845 zip_archives_.clear();
1846 raw_dex_files_.clear();
1847 return true;
1848}
1849
1850bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1851 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1852 return false;
1853 }
1854 if (oat_dex_file->source_.IsZipEntry()) {
1855 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1856 return false;
1857 }
1858 } else if (oat_dex_file->source_.IsRawFile()) {
1859 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1860 return false;
1861 }
1862 } else {
1863 DCHECK(oat_dex_file->source_.IsRawData());
1864 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1865 return false;
1866 }
1867 }
1868
1869 // Update current size and account for the written data.
1870 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1871 size_ += oat_dex_file->dex_file_size_;
1872 size_dex_file_ += oat_dex_file->dex_file_size_;
1873 return true;
1874}
1875
1876bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1877 // Dex files are required to be 4 byte aligned.
1878 size_t original_offset = size_;
1879 size_t offset = RoundUp(original_offset, 4);
1880 size_dex_file_alignment_ += offset - original_offset;
1881
1882 // Seek to the start of the dex file and flush any pending operations in the stream.
1883 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1884 uint32_t start_offset = oat_data_offset_ + offset;
1885 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1886 if (actual_offset != static_cast<off_t>(start_offset)) {
1887 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1888 << " Expected: " << start_offset
1889 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1890 return false;
1891 }
1892 if (!out->Flush()) {
1893 PLOG(ERROR) << "Failed to flush before writing dex file."
1894 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1895 return false;
1896 }
1897 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1898 if (actual_offset != static_cast<off_t>(start_offset)) {
1899 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1900 << " Expected: " << start_offset
1901 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1902 return false;
1903 }
1904
1905 size_ = offset;
1906 oat_dex_file->dex_file_offset_ = offset;
1907 return true;
1908}
1909
1910bool OatWriter::WriteDexFile(OutputStream* rodata,
1911 File* file,
1912 OatDexFile* oat_dex_file,
1913 ZipEntry* dex_file) {
1914 size_t start_offset = oat_data_offset_ + size_;
1915 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1916
1917 // Extract the dex file and get the extracted size.
1918 std::string error_msg;
1919 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1920 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1921 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1922 return false;
1923 }
1924 if (file->Flush() != 0) {
1925 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1926 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1927 return false;
1928 }
1929 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1930 if (extracted_end == static_cast<off_t>(-1)) {
1931 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1932 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1933 return false;
1934 }
1935 if (extracted_end < static_cast<off_t>(start_offset)) {
1936 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1937 << " Start: " << start_offset
1938 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1939 return false;
1940 }
1941 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1942 if (extracted_size < sizeof(DexFile::Header)) {
1943 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1944 << extracted_size << " File: " << oat_dex_file->GetLocation();
1945 return false;
1946 }
1947
1948 // Read the dex file header and extract required data to OatDexFile.
1949 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1950 if (actual_offset != static_cast<off_t>(start_offset)) {
1951 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1952 << " Expected: " << start_offset
1953 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1954 return false;
1955 }
1956 if (!ReadDexFileHeader(file, oat_dex_file)) {
1957 return false;
1958 }
1959 if (extracted_size < oat_dex_file->dex_file_size_) {
1960 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1961 << " file size from header: " << oat_dex_file->dex_file_size_
1962 << " File: " << oat_dex_file->GetLocation();
1963 return false;
1964 }
1965
1966 // Override the checksum from header with the CRC from ZIP entry.
1967 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1968
1969 // Seek both file and stream to the end offset.
1970 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1971 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1972 if (actual_offset != static_cast<off_t>(end_offset)) {
1973 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1974 << " Expected: " << end_offset
1975 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1976 return false;
1977 }
1978 actual_offset = rodata->Seek(end_offset, kSeekSet);
1979 if (actual_offset != static_cast<off_t>(end_offset)) {
1980 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1981 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1982 return false;
1983 }
1984 if (!rodata->Flush()) {
1985 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1986 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1987 return false;
1988 }
1989
1990 // If we extracted more than the size specified in the header, truncate the file.
1991 if (extracted_size > oat_dex_file->dex_file_size_) {
1992 if (file->SetLength(end_offset) != 0) {
1993 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1994 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1995 return false;
1996 }
1997 }
1998
1999 return true;
2000}
2001
2002bool OatWriter::WriteDexFile(OutputStream* rodata,
2003 File* file,
2004 OatDexFile* oat_dex_file,
2005 File* dex_file) {
2006 size_t start_offset = oat_data_offset_ + size_;
2007 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2008
2009 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2010 if (input_offset != static_cast<off_t>(0)) {
2011 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2012 << " Expected: 0"
2013 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2014 return false;
2015 }
2016 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2017 return false;
2018 }
2019
2020 // Copy the input dex file using sendfile().
2021 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2022 PLOG(ERROR) << "Failed to copy dex file to oat file."
2023 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2024 return false;
2025 }
2026 if (file->Flush() != 0) {
2027 PLOG(ERROR) << "Failed to flush dex file."
2028 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2029 return false;
2030 }
2031
2032 // Check file position and seek the stream to the end offset.
2033 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2034 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2035 if (actual_offset != static_cast<off_t>(end_offset)) {
2036 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2037 << " Expected: " << end_offset
2038 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2039 return false;
2040 }
2041 actual_offset = rodata->Seek(end_offset, kSeekSet);
2042 if (actual_offset != static_cast<off_t>(end_offset)) {
2043 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2044 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2045 return false;
2046 }
2047 if (!rodata->Flush()) {
2048 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2049 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2050 return false;
2051 }
2052
2053 return true;
2054}
2055
2056bool OatWriter::WriteDexFile(OutputStream* rodata,
2057 OatDexFile* oat_dex_file,
2058 const uint8_t* dex_file) {
2059 // Note: The raw data has already been checked to contain the header
2060 // and all the data that the header specifies as the file size.
2061 DCHECK(dex_file != nullptr);
2062 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2063 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2064
Vladimir Markoe079e212016-05-25 12:49:49 +01002065 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002066 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2067 << " to " << rodata->GetLocation();
2068 return false;
2069 }
2070 if (!rodata->Flush()) {
2071 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2072 << " File: " << oat_dex_file->GetLocation();
2073 return false;
2074 }
2075
2076 // Update dex file size and resize class offsets in the OatDexFile.
2077 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2078 oat_dex_file->dex_file_size_ = header->file_size_;
2079 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2080 return true;
2081}
2082
2083bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2084 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2085
2086 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2087 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2088 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2089 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2090 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2091 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2092 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2093 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2094 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2095 return false;
2096 }
2097
2098 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2099 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2100
2101 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2102 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2103
2104 // Write OatDexFile.
2105 if (!oat_dex_file->Write(this, rodata)) {
2106 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2107 return false;
2108 }
2109 }
2110
2111 return true;
2112}
2113
2114bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2115 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2116
2117 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2118 if (file->SetLength(new_length) != 0) {
2119 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2120 << "File: " << file->GetPath();
2121 return false;
2122 }
2123 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2124 if (actual_offset != static_cast<off_t>(new_length)) {
2125 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2126 << " Actual: " << actual_offset << " Expected: " << new_length
2127 << " File: " << rodata->GetLocation();
2128 return false;
2129 }
2130 if (!rodata->Flush()) {
2131 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2132 << " File: " << rodata->GetLocation();
2133 return false;
2134 }
2135 return true;
2136}
2137
2138bool OatWriter::OpenDexFiles(
2139 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002140 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002141 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2142 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2143 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2144
2145 if (oat_dex_files_.empty()) {
2146 // Nothing to do.
2147 return true;
2148 }
2149
2150 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2151 size_t length = size_ - map_offset;
2152 std::string error_msg;
2153 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2154 PROT_READ | PROT_WRITE,
2155 MAP_SHARED,
2156 file->Fd(),
2157 oat_data_offset_ + map_offset,
2158 /* low_4gb */ false,
2159 file->GetPath().c_str(),
2160 &error_msg));
2161 if (dex_files_map == nullptr) {
2162 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2163 << " error: " << error_msg;
2164 return false;
2165 }
2166 std::vector<std::unique_ptr<const DexFile>> dex_files;
2167 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2168 // Make sure no one messed with input files while we were copying data.
2169 // At the very least we need consistent file size and number of class definitions.
2170 const uint8_t* raw_dex_file =
2171 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2172 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2173 // Note: ValidateDexFileHeader() already logged an error message.
2174 LOG(ERROR) << "Failed to verify written dex file header!"
2175 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2176 << " ~ " << static_cast<const void*>(raw_dex_file);
2177 return false;
2178 }
2179 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2180 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2181 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2182 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2183 << " Output: " << file->GetPath();
2184 return false;
2185 }
2186 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2187 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2188 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2189 << " Output: " << file->GetPath();
2190 return false;
2191 }
2192
2193 // Now, open the dex file.
2194 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2195 oat_dex_file.dex_file_size_,
2196 oat_dex_file.GetLocation(),
2197 oat_dex_file.dex_file_location_checksum_,
2198 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002199 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002200 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002201 &error_msg));
2202 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002203 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2204 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002205 return false;
2206 }
2207 }
2208
2209 *opened_dex_files_map = std::move(dex_files_map);
2210 *opened_dex_files = std::move(dex_files);
2211 return true;
2212}
2213
2214bool OatWriter::WriteTypeLookupTables(
2215 MemMap* opened_dex_files_map,
2216 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2217 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2218
2219 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2220 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2221 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2222 if (oat_dex_file->lookup_table_offset_ != 0u) {
2223 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2224 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2225 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2226 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2227 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2228 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2229 }
2230 }
2231
2232 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2233 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2234 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2235 return false;
2236 }
2237
2238 return true;
2239}
2240
Vladimir Markof4da6752014-08-01 19:04:18 +01002241bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2242 static const uint8_t kPadding[] = {
2243 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2244 };
2245 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002246 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002247 return false;
2248 }
2249 size_code_alignment_ += aligned_code_delta;
2250 return true;
2251}
2252
Vladimir Marko944da602016-02-19 12:27:55 +00002253void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2254 DCHECK(dex_files_ != nullptr);
2255 DCHECK(relative_patcher_ != nullptr);
2256 DCHECK_NE(oat_data_offset_, 0u);
2257 if (image_writer_ != nullptr && !dex_files_->empty()) {
2258 // The oat data begin may not be initialized yet but the oat file offset is ready.
2259 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2260 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2261 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002262 }
2263}
2264
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002265OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2266 DexFileSource source,
2267 CreateTypeLookupTable create_type_lookup_table)
2268 : source_(source),
2269 create_type_lookup_table_(create_type_lookup_table),
2270 dex_file_size_(0),
2271 offset_(0),
2272 dex_file_location_size_(strlen(dex_file_location)),
2273 dex_file_location_data_(dex_file_location),
2274 dex_file_location_checksum_(0u),
2275 dex_file_offset_(0u),
2276 class_offsets_offset_(0u),
2277 lookup_table_offset_(0u),
2278 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002279}
2280
2281size_t OatWriter::OatDexFile::SizeOf() const {
2282 return sizeof(dex_file_location_size_)
2283 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002284 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002285 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002286 + sizeof(class_offsets_offset_)
2287 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002288}
2289
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002290void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2291 DCHECK_EQ(lookup_table_offset_, 0u);
2292 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2293 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2294 if (table_size != 0u) {
2295 // Type tables are required to be 4 byte aligned.
2296 size_t original_offset = oat_writer->size_;
2297 size_t offset = RoundUp(original_offset, 4);
2298 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2299 lookup_table_offset_ = offset;
2300 oat_writer->size_ = offset + table_size;
2301 oat_writer->size_oat_lookup_table_ += table_size;
2302 }
2303 }
2304}
2305
2306void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2307 DCHECK_EQ(class_offsets_offset_, 0u);
2308 if (!class_offsets_.empty()) {
2309 // Class offsets are required to be 4 byte aligned.
2310 size_t original_offset = oat_writer->size_;
2311 size_t offset = RoundUp(original_offset, 4);
2312 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2313 class_offsets_offset_ = offset;
2314 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2315 }
2316}
2317
2318bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2319 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002320 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002321
Vladimir Markoe079e212016-05-25 12:49:49 +01002322 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002323 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002324 return false;
2325 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002326 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002327
Vladimir Markoe079e212016-05-25 12:49:49 +01002328 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002329 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002330 return false;
2331 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002332 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002333
Vladimir Markoe079e212016-05-25 12:49:49 +01002334 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002335 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002336 return false;
2337 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002338 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002339
Vladimir Markoe079e212016-05-25 12:49:49 +01002340 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002341 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002342 return false;
2343 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002344 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345
Vladimir Markoe079e212016-05-25 12:49:49 +01002346 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002347 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2348 return false;
2349 }
2350 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2351
Vladimir Markoe079e212016-05-25 12:49:49 +01002352 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002353 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2354 return false;
2355 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002356 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002357
2358 return true;
2359}
2360
2361bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002362 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002363 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2364 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002365 return false;
2366 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002368 return true;
2369}
2370
Brian Carlstromba150c32013-08-27 17:31:03 -07002371OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002372 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002373 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002374 mirror::Class::Status status)
2375 : compiled_methods_(compiled_methods) {
2376 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002377 CHECK_LE(num_non_null_compiled_methods, num_methods);
2378
Brian Carlstrom265091e2013-01-30 14:08:26 -08002379 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002380 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2381
2382 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2383 // apply when there are 0 methods, we just arbitrarily say that 0
2384 // methods means kOatClassNoneCompiled and that we won't use
2385 // kOatClassAllCompiled unless there is at least one compiled
2386 // method. This means in an interpretter only system, we can assert
2387 // that all classes are kOatClassNoneCompiled.
2388 if (num_non_null_compiled_methods == 0) {
2389 type_ = kOatClassNoneCompiled;
2390 } else if (num_non_null_compiled_methods == num_methods) {
2391 type_ = kOatClassAllCompiled;
2392 } else {
2393 type_ = kOatClassSomeCompiled;
2394 }
2395
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002396 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002397 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002398 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002399
2400 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2401 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002402 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002403 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2404 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2405 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2406 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002407 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002408 method_bitmap_size_ = 0;
2409 }
2410
2411 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002412 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002413 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002414 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2415 } else {
2416 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2417 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2418 if (type_ == kOatClassSomeCompiled) {
2419 method_bitmap_->SetBit(i);
2420 }
2421 }
2422 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002423}
2424
Brian Carlstrom265091e2013-01-30 14:08:26 -08002425size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2426 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002427 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2428 if (method_offset == 0) {
2429 return 0;
2430 }
2431 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002432}
2433
2434size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2435 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002436 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002437}
2438
2439size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002440 return sizeof(status_)
2441 + sizeof(type_)
2442 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2443 + method_bitmap_size_
2444 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002445}
2446
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002447bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002448 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002449 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002450 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002451 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002452 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002453 return false;
2454 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002455 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002456
Vladimir Markoe079e212016-05-25 12:49:49 +01002457 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002458 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002459 return false;
2460 }
2461 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002462
Brian Carlstromba150c32013-08-27 17:31:03 -07002463 if (method_bitmap_size_ != 0) {
2464 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002465 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002466 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002467 return false;
2468 }
2469 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002470
Vladimir Markoe079e212016-05-25 12:49:49 +01002471 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002472 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002473 return false;
2474 }
2475 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2476 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002477
Vladimir Markoe079e212016-05-25 12:49:49 +01002478 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002479 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002480 return false;
2481 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002482 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002483 return true;
2484}
2485
Brian Carlstrome24fa612011-09-29 00:53:55 -07002486} // namespace art