blob: b32199f0a50059d21852d71857ee084b0fad56ed [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000026#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070029#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070030#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000031#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000032#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000033#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "dex_file-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000035#include "driver/compiler_driver.h"
36#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010037#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030039#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010040#include "image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000041#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000042#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/array.h"
44#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010045#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010047#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070048#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070049#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010052#include "utils/dex_cache_arrays_layout-inl.h"
jeffhaoec014232012-09-05 10:42:25 -070053#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000054#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070055
56namespace art {
57
Vladimir Marko9bdf1082016-01-21 12:15:52 +000058namespace { // anonymous namespace
59
60typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
61
62const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
63 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
64}
65
Vladimir Markoe079e212016-05-25 12:49:49 +010066class ChecksumUpdatingOutputStream : public OutputStream {
67 public:
68 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
69 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
70
71 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
72 oat_header_->UpdateChecksum(buffer, byte_count);
73 return out_->WriteFully(buffer, byte_count);
74 }
75
76 off_t Seek(off_t offset, Whence whence) OVERRIDE {
77 return out_->Seek(offset, whence);
78 }
79
80 bool Flush() OVERRIDE {
81 return out_->Flush();
82 }
83
84 private:
85 OutputStream* const out_;
86 OatHeader* const oat_header_;
87};
88
Vladimir Marko9bdf1082016-01-21 12:15:52 +000089} // anonymous namespace
90
91// Defines the location of the raw dex file to write.
92class OatWriter::DexFileSource {
93 public:
94 explicit DexFileSource(ZipEntry* zip_entry)
95 : type_(kZipEntry), source_(zip_entry) {
96 DCHECK(source_ != nullptr);
97 }
98
99 explicit DexFileSource(File* raw_file)
100 : type_(kRawFile), source_(raw_file) {
101 DCHECK(source_ != nullptr);
102 }
103
104 explicit DexFileSource(const uint8_t* dex_file)
105 : type_(kRawData), source_(dex_file) {
106 DCHECK(source_ != nullptr);
107 }
108
109 bool IsZipEntry() const { return type_ == kZipEntry; }
110 bool IsRawFile() const { return type_ == kRawFile; }
111 bool IsRawData() const { return type_ == kRawData; }
112
113 ZipEntry* GetZipEntry() const {
114 DCHECK(IsZipEntry());
115 DCHECK(source_ != nullptr);
116 return static_cast<ZipEntry*>(const_cast<void*>(source_));
117 }
118
119 File* GetRawFile() const {
120 DCHECK(IsRawFile());
121 DCHECK(source_ != nullptr);
122 return static_cast<File*>(const_cast<void*>(source_));
123 }
124
125 const uint8_t* GetRawData() const {
126 DCHECK(IsRawData());
127 DCHECK(source_ != nullptr);
128 return static_cast<const uint8_t*>(source_);
129 }
130
131 void Clear() {
132 type_ = kNone;
133 source_ = nullptr;
134 }
135
136 private:
137 enum Type {
138 kNone,
139 kZipEntry,
140 kRawFile,
141 kRawData,
142 };
143
144 Type type_;
145 const void* source_;
146};
147
Vladimir Marko49b0f452015-12-10 13:49:19 +0000148class OatWriter::OatClass {
149 public:
150 OatClass(size_t offset,
151 const dchecked_vector<CompiledMethod*>& compiled_methods,
152 uint32_t num_non_null_compiled_methods,
153 mirror::Class::Status status);
154 OatClass(OatClass&& src) = default;
155 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
156 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
157 size_t SizeOf() const;
158 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
159
160 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
161 return compiled_methods_[class_def_method_index];
162 }
163
164 // Offset of start of OatClass from beginning of OatHeader. It is
165 // used to validate file position when writing.
166 size_t offset_;
167
168 // CompiledMethods for each class_def_method_index, or null if no method is available.
169 dchecked_vector<CompiledMethod*> compiled_methods_;
170
171 // Offset from OatClass::offset_ to the OatMethodOffsets for the
172 // class_def_method_index. If 0, it means the corresponding
173 // CompiledMethod entry in OatClass::compiled_methods_ should be
174 // null and that the OatClass::type_ should be kOatClassBitmap.
175 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
176
177 // Data to write.
178
179 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
180 int16_t status_;
181
182 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
183 uint16_t type_;
184
185 uint32_t method_bitmap_size_;
186
187 // bit vector indexed by ClassDef method index. When
188 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
189 // method has an OatMethodOffsets in methods_offsets_, otherwise
190 // the entry was ommited to save space. If OatClassType::type_ is
191 // not is kOatClassBitmap, the bitmap will be null.
192 std::unique_ptr<BitVector> method_bitmap_;
193
194 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
195 // present in the OatClass. Note that some may be missing if
196 // OatClass::compiled_methods_ contains null values (and
197 // oat_method_offsets_offsets_from_oat_class_ should contain 0
198 // values in this case).
199 dchecked_vector<OatMethodOffsets> method_offsets_;
200 dchecked_vector<OatQuickMethodHeader> method_headers_;
201
202 private:
203 size_t GetMethodOffsetsRawSize() const {
204 return method_offsets_.size() * sizeof(method_offsets_[0]);
205 }
206
207 DISALLOW_COPY_AND_ASSIGN(OatClass);
208};
209
210class OatWriter::OatDexFile {
211 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000212 OatDexFile(const char* dex_file_location,
213 DexFileSource source,
214 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000215 OatDexFile(OatDexFile&& src) = default;
216
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000217 const char* GetLocation() const {
218 return dex_file_location_data_;
219 }
220
221 void ReserveTypeLookupTable(OatWriter* oat_writer);
222 void ReserveClassOffsets(OatWriter* oat_writer);
223
Vladimir Marko49b0f452015-12-10 13:49:19 +0000224 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 bool Write(OatWriter* oat_writer, OutputStream* out) const;
226 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
227
228 // The source of the dex file.
229 DexFileSource source_;
230
231 // Whether to create the type lookup table.
232 CreateTypeLookupTable create_type_lookup_table_;
233
234 // Dex file size. Initialized when writing the dex file.
235 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236
237 // Offset of start of OatDexFile from beginning of OatHeader. It is
238 // used to validate file position when writing.
239 size_t offset_;
240
241 // Data to write.
242 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000243 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000244 uint32_t dex_file_location_checksum_;
245 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000246 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000247 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000248
249 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000250 dchecked_vector<uint32_t> class_offsets_;
251
252 private:
253 size_t GetClassOffsetsRawSize() const {
254 return class_offsets_.size() * sizeof(class_offsets_[0]);
255 }
256
257 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
258};
259
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100260#define DCHECK_OFFSET() \
261 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
262 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
263
264#define DCHECK_OFFSET_() \
265 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
266 << "file_offset=" << file_offset << " offset_=" << offset_
267
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000268OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
269 : write_state_(WriteState::kAddingDexFileSources),
270 timings_(timings),
271 raw_dex_files_(),
272 zip_archives_(),
273 zipped_dex_files_(),
274 zipped_dex_file_locations_(),
275 compiler_driver_(nullptr),
276 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800277 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000278 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100279 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000280 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100281 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700282 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700283 size_dex_file_alignment_(0),
284 size_executable_offset_alignment_(0),
285 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700286 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700287 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700288 size_interpreter_to_interpreter_bridge_(0),
289 size_interpreter_to_compiled_code_bridge_(0),
290 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800291 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700292 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700293 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700294 size_quick_to_interpreter_bridge_(0),
295 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100296 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700297 size_code_(0),
298 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100299 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100300 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700301 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700302 size_oat_dex_file_location_size_(0),
303 size_oat_dex_file_location_data_(0),
304 size_oat_dex_file_location_checksum_(0),
305 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000306 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000307 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000308 size_oat_lookup_table_alignment_(0),
309 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000310 size_oat_class_offsets_alignment_(0),
311 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700312 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700313 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700314 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100315 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000316 relative_patcher_(nullptr),
317 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000318}
319
320bool OatWriter::AddDexFileSource(const char* filename,
321 const char* location,
322 CreateTypeLookupTable create_type_lookup_table) {
323 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
324 uint32_t magic;
325 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700326 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
327 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000328 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
329 return false;
330 } else if (IsDexMagic(magic)) {
331 // The file is open for reading, not writing, so it's OK to let the File destructor
332 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700333 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000334 oat_dex_files_.emplace_back(location,
335 DexFileSource(raw_dex_files_.back().get()),
336 create_type_lookup_table);
337 } else if (IsZipMagic(magic)) {
338 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
339 return false;
340 }
341 } else {
342 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
343 return false;
344 }
345 return true;
346}
347
348// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700349bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000350 const char* location,
351 CreateTypeLookupTable create_type_lookup_table) {
352 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
353 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700354 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000355 ZipArchive* zip_archive = zip_archives_.back().get();
356 if (zip_archive == nullptr) {
357 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
358 << error_msg;
359 return false;
360 }
361 for (size_t i = 0; ; ++i) {
362 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
363 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
364 if (entry == nullptr) {
365 break;
366 }
367 zipped_dex_files_.push_back(std::move(entry));
368 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
369 const char* full_location = zipped_dex_file_locations_.back().c_str();
370 oat_dex_files_.emplace_back(full_location,
371 DexFileSource(zipped_dex_files_.back().get()),
372 create_type_lookup_table);
373 }
374 if (zipped_dex_file_locations_.empty()) {
375 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
376 return false;
377 }
378 return true;
379}
380
381// Add dex file source from raw memory.
382bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
383 const char* location,
384 uint32_t location_checksum,
385 CreateTypeLookupTable create_type_lookup_table) {
386 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
387 if (data.size() < sizeof(DexFile::Header)) {
388 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
389 << data.size() << " File: " << location;
390 return false;
391 }
392 if (!ValidateDexFileHeader(data.data(), location)) {
393 return false;
394 }
395 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
396 if (data.size() < header->file_size_) {
397 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
398 << " file size from header: " << header->file_size_ << " File: " << location;
399 return false;
400 }
401
402 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
403 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
404 return true;
405}
406
407dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
408 dchecked_vector<const char*> locations;
409 locations.reserve(oat_dex_files_.size());
410 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
411 locations.push_back(oat_dex_file.GetLocation());
412 }
413 return locations;
414}
415
416bool OatWriter::WriteAndOpenDexFiles(
417 OutputStream* rodata,
418 File* file,
419 InstructionSet instruction_set,
420 const InstructionSetFeatures* instruction_set_features,
421 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800422 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000423 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
424 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
425 CHECK(write_state_ == WriteState::kAddingDexFileSources);
426
427 size_t offset = InitOatHeader(instruction_set,
428 instruction_set_features,
429 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
430 key_value_store);
431 offset = InitOatDexFiles(offset);
432 size_ = offset;
433
434 std::unique_ptr<MemMap> dex_files_map;
435 std::vector<std::unique_ptr<const DexFile>> dex_files;
436 if (!WriteDexFiles(rodata, file)) {
437 return false;
438 }
439 // Reserve space for type lookup tables and update type_lookup_table_offset_.
440 for (OatDexFile& oat_dex_file : oat_dex_files_) {
441 oat_dex_file.ReserveTypeLookupTable(this);
442 }
443 size_t size_after_type_lookup_tables = size_;
444 // Reserve space for class offsets and update class_offsets_offset_.
445 for (OatDexFile& oat_dex_file : oat_dex_files_) {
446 oat_dex_file.ReserveClassOffsets(this);
447 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100448 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
449 if (!WriteOatDexFiles(&checksum_updating_rodata) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000450 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800451 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
453 return false;
454 }
455
Vladimir Markoe079e212016-05-25 12:49:49 +0100456 // Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
457 // piece would be difficult because we're not using the OutpuStream directly.
458 if (!oat_dex_files_.empty()) {
459 size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
460 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
461 }
462
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000463 *opened_dex_files_map = std::move(dex_files_map);
464 *opened_dex_files = std::move(dex_files);
465 write_state_ = WriteState::kPrepareLayout;
466 return true;
467}
468
469void OatWriter::PrepareLayout(const CompilerDriver* compiler,
470 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000471 const std::vector<const DexFile*>& dex_files,
472 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000473 CHECK(write_state_ == WriteState::kPrepareLayout);
474
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000475 compiler_driver_ = compiler;
476 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000477 dex_files_ = &dex_files;
478 relative_patcher_ = relative_patcher;
479 SetMultiOatRelativePatcherAdjustment();
480
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 if (compiling_boot_image_) {
482 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800483 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100484 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000485 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100486
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000487 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800488 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800490 offset = InitOatClasses(offset);
491 }
492 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100494 offset = InitOatMaps(offset);
495 }
496 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800498 offset = InitOatCode(offset);
499 }
500 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000501 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800502 offset = InitOatCodeDexFiles(offset);
503 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700504 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700505
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800506 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100507 // Allocate space for app dex cache arrays in the .bss section.
508 size_t bss_start = RoundUp(size_, kPageSize);
509 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
510 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000511 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100512 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
513 DexCacheArraysLayout layout(pointer_size, dex_file);
514 bss_size_ += layout.Size();
515 }
516 }
517
Brian Carlstrome24fa612011-09-29 00:53:55 -0700518 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800519 if (compiling_boot_image_) {
520 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000521 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800522 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000523
524 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700525}
526
Ian Rogers0571d352011-11-03 19:51:38 -0700527OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700528}
529
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100530class OatWriter::DexMethodVisitor {
531 public:
532 DexMethodVisitor(OatWriter* writer, size_t offset)
533 : writer_(writer),
534 offset_(offset),
535 dex_file_(nullptr),
536 class_def_index_(DexFile::kDexNoIndex) {
537 }
538
539 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
540 DCHECK(dex_file_ == nullptr);
541 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
542 dex_file_ = dex_file;
543 class_def_index_ = class_def_index;
544 return true;
545 }
546
547 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
548
549 virtual bool EndClass() {
550 if (kIsDebugBuild) {
551 dex_file_ = nullptr;
552 class_def_index_ = DexFile::kDexNoIndex;
553 }
554 return true;
555 }
556
557 size_t GetOffset() const {
558 return offset_;
559 }
560
561 protected:
562 virtual ~DexMethodVisitor() { }
563
564 OatWriter* const writer_;
565
566 // The offset is usually advanced for each visited method by the derived class.
567 size_t offset_;
568
569 // The dex file and class def index are set in StartClass().
570 const DexFile* dex_file_;
571 size_t class_def_index_;
572};
573
574class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
575 public:
576 OatDexMethodVisitor(OatWriter* writer, size_t offset)
577 : DexMethodVisitor(writer, offset),
578 oat_class_index_(0u),
579 method_offsets_index_(0u) {
580 }
581
582 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
583 DexMethodVisitor::StartClass(dex_file, class_def_index);
584 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
585 method_offsets_index_ = 0u;
586 return true;
587 }
588
589 bool EndClass() {
590 ++oat_class_index_;
591 return DexMethodVisitor::EndClass();
592 }
593
594 protected:
595 size_t oat_class_index_;
596 size_t method_offsets_index_;
597};
598
599class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
600 public:
601 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
602 : DexMethodVisitor(writer, offset),
603 compiled_methods_(),
604 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000605 size_t num_classes = 0u;
606 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
607 num_classes += oat_dex_file.class_offsets_.size();
608 }
609 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100610 compiled_methods_.reserve(256u);
611 }
612
613 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
614 DexMethodVisitor::StartClass(dex_file, class_def_index);
615 compiled_methods_.clear();
616 num_non_null_compiled_methods_ = 0u;
617 return true;
618 }
619
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300620 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
621 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100622 // Fill in the compiled_methods_ array for methods that have a
623 // CompiledMethod. We track the number of non-null entries in
624 // num_non_null_compiled_methods_ since we only want to allocate
625 // OatMethodOffsets for the compiled methods.
626 uint32_t method_idx = it.GetMemberIndex();
627 CompiledMethod* compiled_method =
628 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
629 compiled_methods_.push_back(compiled_method);
630 if (compiled_method != nullptr) {
631 ++num_non_null_compiled_methods_;
632 }
633 return true;
634 }
635
636 bool EndClass() {
637 ClassReference class_ref(dex_file_, class_def_index_);
638 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
639 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700640 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100641 status = compiled_class->GetStatus();
642 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
643 status = mirror::Class::kStatusError;
644 } else {
645 status = mirror::Class::kStatusNotReady;
646 }
647
Vladimir Marko49b0f452015-12-10 13:49:19 +0000648 writer_->oat_classes_.emplace_back(offset_,
649 compiled_methods_,
650 num_non_null_compiled_methods_,
651 status);
652 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100653 return DexMethodVisitor::EndClass();
654 }
655
656 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000657 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100658 size_t num_non_null_compiled_methods_;
659};
660
661class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
662 public:
663 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100664 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100665 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100666 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100667 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
668 }
669
670 bool EndClass() {
671 OatDexMethodVisitor::EndClass();
672 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100673 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100674 }
675 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100676 }
677
678 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700679 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000680 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100681 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
682
683 if (compiled_method != nullptr) {
684 // Derived from CompiledMethod.
685 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100686
Vladimir Marko35831e82015-09-11 11:59:18 +0100687 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
688 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800689 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800690
David Srbecky009e2a62015-04-15 02:46:30 +0100691 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100692 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800693 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000694 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000695 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
696 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800697 // Duplicate methods, we want the same code for both of them so that the oat writer puts
698 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800699 } else {
700 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100701 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800702 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000703 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100704 quick_code_offset = dedupe_map_.GetOrCreate(
705 compiled_method,
706 [this, &deduped, compiled_method, &it, thumb_offset]() {
707 deduped = false;
708 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
709 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800710 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100711
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100712 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000713 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100714 // TODO: Should this be a hard failure?
715 LOG(WARNING) << "Multiple definitions of "
716 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000717 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
718 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100719 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000720 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100721 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800722 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723
Elliott Hughes956af0f2014-12-11 14:34:28 -0800724 // Update quick method header.
725 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
726 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800727 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100728 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
729 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100730 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800731 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
732 // to 0-offset and we need to adjust it by code_offset.
733 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100734 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800735 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100736 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800737 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800738 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
739 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
740 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100741 *method_header = OatQuickMethodHeader(vmap_table_offset,
742 frame_size_in_bytes,
743 core_spill_mask,
744 fp_spill_mask,
745 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100746
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000747 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800748 // Update offsets. (Checksum is updated when writing.)
749 offset_ += sizeof(*method_header); // Method header is prepended before code.
750 offset_ += code_size;
751 // Record absolute patch locations.
752 if (!compiled_method->GetPatches().empty()) {
753 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
754 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000755 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100756 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100757 }
758 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100759 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800760 }
Alex Light78382fa2014-06-06 15:45:32 -0700761
David Srbecky91cc06c2016-03-07 16:13:58 +0000762 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000763 // Exclude quickened dex methods (code_size == 0) since they have no native code.
764 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
765 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800766 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000767 debug::MethodDebugInfo info = debug::MethodDebugInfo();
768 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000769 info.dex_file = dex_file_;
770 info.class_def_index = class_def_index_;
771 info.dex_method_index = it.GetMemberIndex();
772 info.access_flags = it.GetMethodAccessFlags();
773 info.code_item = it.GetMethodCodeItem();
774 info.isa = compiled_method->GetInstructionSet();
775 info.deduped = deduped;
776 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
777 info.is_optimized = method_header->IsOptimized();
778 info.is_code_address_text_relative = true;
779 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
780 info.code_size = code_size;
781 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
782 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
783 info.cfi = compiled_method->GetCFIInfo();
784 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100785 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100786
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100787 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
788 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
789 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100790 ++method_offsets_index_;
791 }
792
793 return true;
794 }
795
796 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000797 struct CodeOffsetsKeyComparator {
798 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100799 // Code is deduplicated by CompilerDriver, compare only data pointers.
800 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
801 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000802 }
803 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100804 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
805 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000806 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100807 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
808 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000809 }
810 return false;
811 }
812 };
813
David Srbecky009e2a62015-04-15 02:46:30 +0100814 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
815 const ClassDataItemIterator& it,
816 uint32_t thumb_offset) {
817 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100818 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100819 offset_ = compiled_method->AlignCode(offset_);
820 DCHECK_ALIGNED_PARAM(offset_,
821 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
822 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
823 }
824
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100825 // Deduplication is already done on a pointer basis by the compiler driver,
826 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100827 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100828
David Srbecky009e2a62015-04-15 02:46:30 +0100829 // Cache of compiler's --debuggable option.
830 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100831};
832
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
834 public:
835 InitMapMethodVisitor(OatWriter* writer, size_t offset)
836 : OatDexMethodVisitor(writer, offset) {
837 }
838
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700839 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700840 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000841 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100842 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
843
844 if (compiled_method != nullptr) {
845 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100846 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100847
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100848 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100849 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100850 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100851 size_t offset = dedupe_map_.GetOrCreate(
852 map.data(),
853 [this, map_size]() {
854 uint32_t new_offset = offset_;
855 offset_ += map_size;
856 return new_offset;
857 });
858 // Code offset is not initialized yet, so set the map offset to 0u-offset.
859 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
860 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100861 }
862 ++method_offsets_index_;
863 }
864
865 return true;
866 }
867
868 private:
869 // Deduplication is already done on a pointer basis by the compiler driver,
870 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100871 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100872};
873
874class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
875 public:
876 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800877 : OatDexMethodVisitor(writer, offset),
878 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100879 }
880
881 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700882 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800883 const DexFile::TypeId& type_id =
884 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
885 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
886 // Skip methods that are not in the image.
887 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
888 return true;
889 }
890
Vladimir Marko49b0f452015-12-10 13:49:19 +0000891 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100892 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
893
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800894 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100895 if (compiled_method != nullptr) {
896 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
897 offsets = oat_class->method_offsets_[method_offsets_index_];
898 ++method_offsets_index_;
899 }
900
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100901 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100902 // Unchecked as we hold mutator_lock_ on entry.
903 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800904 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700905 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
906 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800907 ArtMethod* method;
908 if (writer_->HasBootImage()) {
909 const InvokeType invoke_type = it.GetMethodInvokeType(
910 dex_file_->GetClassDef(class_def_index_));
911 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
912 *dex_file_,
913 it.GetMemberIndex(),
914 dex_cache,
915 ScopedNullHandle<mirror::ClassLoader>(),
916 nullptr,
917 invoke_type);
918 if (method == nullptr) {
919 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
920 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
921 soa.Self()->AssertPendingException();
922 mirror::Throwable* exc = soa.Self()->GetException();
923 std::string dump = exc->Dump();
924 LOG(FATAL) << dump;
925 UNREACHABLE();
926 }
927 } else {
928 // Should already have been resolved by the compiler, just peek into the dex cache.
929 // It may not be resolved if the class failed to verify, in this case, don't set the
930 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
931 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700932 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800933 if (method != nullptr &&
934 compiled_method != nullptr &&
935 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100936 method->SetEntryPointFromQuickCompiledCodePtrSize(
937 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
938 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939
940 return true;
941 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800942
943 protected:
944 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100945};
946
947class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
948 public:
949 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100950 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100951 : OatDexMethodVisitor(writer, relative_offset),
952 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100953 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100954 soa_(Thread::Current()),
955 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100956 class_linker_(Runtime::Current()->GetClassLinker()),
957 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100958 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800959 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100960 // If we're creating the image, the address space must be ready so that we can apply patches.
961 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100962 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 }
964
Vladimir Markof4da6752014-08-01 19:04:18 +0100965 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100966 }
967
968 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700969 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100970 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
971 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700972 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000973 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100974 }
975 return true;
976 }
977
Mathieu Chartier90443472015-07-16 20:32:27 -0700978 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100979 bool result = OatDexMethodVisitor::EndClass();
980 if (oat_class_index_ == writer_->oat_classes_.size()) {
981 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000982 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100983 if (UNLIKELY(offset_ == 0u)) {
984 PLOG(ERROR) << "Failed to write final relative call thunks";
985 result = false;
986 }
987 }
988 return result;
989 }
990
991 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700992 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000993 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100994 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
995
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700996 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
997 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700998 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100999 size_t file_offset = file_offset_;
1000 OutputStream* out = out_;
1001
Vladimir Marko35831e82015-09-11 11:59:18 +01001002 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1003 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001004
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001005 // Deduplicate code arrays.
1006 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1007 if (method_offsets.code_offset_ > offset_) {
1008 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1009 if (offset_ == 0u) {
1010 ReportWriteFailure("relative call thunk", it);
1011 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001012 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001013 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1014 uint32_t aligned_code_delta = aligned_offset - offset_;
1015 if (aligned_code_delta != 0) {
1016 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1017 ReportWriteFailure("code alignment padding", it);
1018 return false;
1019 }
1020 offset_ += aligned_code_delta;
1021 DCHECK_OFFSET_();
1022 }
1023 DCHECK_ALIGNED_PARAM(offset_,
1024 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1025 DCHECK_EQ(method_offsets.code_offset_,
1026 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1027 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1028 const OatQuickMethodHeader& method_header =
1029 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001030 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001031 ReportWriteFailure("method header", it);
1032 return false;
1033 }
1034 writer_->size_method_header_ += sizeof(method_header);
1035 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001036 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001037
1038 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001039 patched_code_.assign(quick_code.begin(), quick_code.end());
1040 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001041 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001042 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001043 switch (patch.GetType()) {
1044 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001045 // NOTE: Relative calls across oat files are not supported.
1046 uint32_t target_offset = GetTargetOffset(patch);
1047 writer_->relative_patcher_->PatchCall(&patched_code_,
1048 literal_offset,
1049 offset_ + literal_offset,
1050 target_offset);
1051 break;
1052 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001053 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001054 uint32_t target_offset = GetDexCacheOffset(patch);
1055 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1056 patch,
1057 offset_ + literal_offset,
1058 target_offset);
1059 break;
1060 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001061 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001062 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1063 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1064 patch,
1065 offset_ + literal_offset,
1066 target_offset);
1067 break;
1068 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001069 case LinkerPatch::Type::kTypeRelative: {
1070 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1071 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1072 patch,
1073 offset_ + literal_offset,
1074 target_offset);
1075 break;
1076 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001077 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001078 uint32_t target_offset = GetTargetOffset(patch);
1079 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1080 break;
1081 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001082 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001083 ArtMethod* method = GetTargetMethod(patch);
1084 PatchMethodAddress(&patched_code_, literal_offset, method);
1085 break;
1086 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001087 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001088 mirror::String* string = GetTargetString(patch);
1089 PatchObjectAddress(&patched_code_, literal_offset, string);
1090 break;
1091 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001092 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001093 mirror::Class* type = GetTargetType(patch);
1094 PatchObjectAddress(&patched_code_, literal_offset, type);
1095 break;
1096 }
1097 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001098 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001099 break;
1100 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001101 }
1102 }
1103 }
1104
Vladimir Markoe079e212016-05-25 12:49:49 +01001105 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001106 ReportWriteFailure("method code", it);
1107 return false;
1108 }
1109 writer_->size_code_ += code_size;
1110 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001111 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001112 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001113 ++method_offsets_index_;
1114 }
1115
1116 return true;
1117 }
1118
1119 private:
1120 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001121 const size_t file_offset_;
1122 const ScopedObjectAccess soa_;
1123 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001124 ClassLinker* const class_linker_;
1125 mirror::DexCache* dex_cache_;
1126 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001127
1128 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1129 PLOG(ERROR) << "Failed to write " << what << " for "
1130 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1131 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001132
Mathieu Chartiere401d142015-04-22 13:56:20 -07001133 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001134 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001135 MethodReference ref = patch.TargetMethod();
1136 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001137 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1138 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001139 ArtMethod* method = dex_cache->GetResolvedMethod(
1140 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001141 CHECK(method != nullptr);
1142 return method;
1143 }
1144
Mathieu Chartier90443472015-07-16 20:32:27 -07001145 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001146 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1147 // If there's no new compiled code, either we're compiling an app and the target method
1148 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001149 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001150 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001151 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001152 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1153 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1154 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001155 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001156 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1157 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1158 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1159 target_offset = PointerToLowMemUInt32(oat_code_offset);
1160 } else {
1161 target_offset = target->IsNative()
1162 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1163 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1164 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001165 }
1166 return target_offset;
1167 }
1168
Vladimir Marko052164a2016-04-27 13:54:18 +01001169 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
1170 SHARED_REQUIRES(Locks::mutator_lock_) {
1171 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001172 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001173 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1174 }
1175
1176 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1177 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001178 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1179 CHECK(type != nullptr);
1180 return type;
1181 }
1182
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001183 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001184 mirror::DexCache* dex_cache = GetDexCache(patch.TargetStringDexFile());
1185 mirror::String* string = dex_cache->GetResolvedString(patch.TargetStringIndex());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001186 DCHECK(string != nullptr);
1187 DCHECK(writer_->HasBootImage() ||
1188 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1189 return string;
1190 }
1191
Mathieu Chartier90443472015-07-16 20:32:27 -07001192 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001193 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001194 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1195 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1196 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1197 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001198 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001199 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001200 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1201 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001202 }
1203 }
1204
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001205 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1206 DCHECK(writer_->HasBootImage());
1207 object = writer_->image_writer_->GetImageAddress(object);
1208 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1209 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1210 // TODO: Clean up offset types. The target offset must be treated as signed.
1211 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1212 }
1213
Vladimir Markof4da6752014-08-01 19:04:18 +01001214 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001215 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001216 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001217 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001218 } else {
1219 // NOTE: We're using linker patches for app->boot references when the image can
1220 // be relocated and therefore we need to emit .oat_patches. We're not using this
1221 // for app->app references, so check that the object is in the image space.
1222 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001223 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001224 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001225 uint32_t address = PointerToLowMemUInt32(object);
1226 DCHECK_LE(offset + 4, code->size());
1227 uint8_t* data = &(*code)[offset];
1228 data[0] = address & 0xffu;
1229 data[1] = (address >> 8) & 0xffu;
1230 data[2] = (address >> 16) & 0xffu;
1231 data[3] = (address >> 24) & 0xffu;
1232 }
1233
Mathieu Chartiere401d142015-04-22 13:56:20 -07001234 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001235 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001236 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001237 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001238 } else if (kIsDebugBuild) {
1239 // NOTE: We're using linker patches for app->boot references when the image can
1240 // be relocated and therefore we need to emit .oat_patches. We're not using this
1241 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001242 std::vector<gc::space::ImageSpace*> image_spaces =
1243 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1244 bool contains_method = false;
1245 for (gc::space::ImageSpace* image_space : image_spaces) {
1246 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1247 contains_method |=
1248 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1249 }
1250 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001251 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001252 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001253 uint32_t address = PointerToLowMemUInt32(method);
1254 DCHECK_LE(offset + 4, code->size());
1255 uint8_t* data = &(*code)[offset];
1256 data[0] = address & 0xffu;
1257 data[1] = (address >> 8) & 0xffu;
1258 data[2] = (address >> 16) & 0xffu;
1259 data[3] = (address >> 24) & 0xffu;
1260 }
1261
Vladimir Markof4da6752014-08-01 19:04:18 +01001262 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001263 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001264 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001265 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001266 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1267 // TODO: Clean up offset types.
1268 // The target_offset must be treated as signed for cross-oat patching.
1269 const void* target = reinterpret_cast<const void*>(
1270 writer_->image_writer_->GetOatDataBegin(oat_index) +
1271 static_cast<int32_t>(target_offset));
1272 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001273 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001274 DCHECK_LE(offset + 4, code->size());
1275 uint8_t* data = &(*code)[offset];
1276 data[0] = address & 0xffu;
1277 data[1] = (address >> 8) & 0xffu;
1278 data[2] = (address >> 16) & 0xffu;
1279 data[3] = (address >> 24) & 0xffu;
1280 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001281};
1282
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001283class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1284 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001285 WriteMapMethodVisitor(OatWriter* writer,
1286 OutputStream* out,
1287 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001288 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001289 : OatDexMethodVisitor(writer, relative_offset),
1290 out_(out),
1291 file_offset_(file_offset) {
1292 }
1293
1294 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001295 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001296 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1297
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001298 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001299 size_t file_offset = file_offset_;
1300 OutputStream* out = out_;
1301
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001302 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1303 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001304 ++method_offsets_index_;
1305
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001306 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1307 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1308 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1309 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1310
1311 if (map_offset != 0u) {
1312 // Transform map_offset to actual oat data offset.
1313 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1314 DCHECK_NE(map_offset, 0u);
1315 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1316
1317 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1318 size_t map_size = map.size() * sizeof(map[0]);
1319 if (map_offset == offset_) {
1320 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001321 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001322 ReportWriteFailure(it);
1323 return false;
1324 }
1325 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001326 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001327 }
1328 DCHECK_OFFSET_();
1329 }
1330
1331 return true;
1332 }
1333
1334 private:
1335 OutputStream* const out_;
1336 size_t const file_offset_;
1337
1338 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001339 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001340 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1341 }
1342};
1343
1344// Visit all methods from all classes in all dex files with the specified visitor.
1345bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1346 for (const DexFile* dex_file : *dex_files_) {
1347 const size_t class_def_count = dex_file->NumClassDefs();
1348 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1349 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1350 return false;
1351 }
1352 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001353 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001354 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001355 ClassDataItemIterator it(*dex_file, class_data);
1356 while (it.HasNextStaticField()) {
1357 it.Next();
1358 }
1359 while (it.HasNextInstanceField()) {
1360 it.Next();
1361 }
1362 size_t class_def_method_index = 0u;
1363 while (it.HasNextDirectMethod()) {
1364 if (!visitor->VisitMethod(class_def_method_index, it)) {
1365 return false;
1366 }
1367 ++class_def_method_index;
1368 it.Next();
1369 }
1370 while (it.HasNextVirtualMethod()) {
1371 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1372 return false;
1373 }
1374 ++class_def_method_index;
1375 it.Next();
1376 }
1377 }
1378 if (UNLIKELY(!visitor->EndClass())) {
1379 return false;
1380 }
1381 }
1382 }
1383 return true;
1384}
1385
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001386size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1387 const InstructionSetFeatures* instruction_set_features,
1388 uint32_t num_dex_files,
1389 SafeMap<std::string, std::string>* key_value_store) {
1390 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1391 oat_header_.reset(OatHeader::Create(instruction_set,
1392 instruction_set_features,
1393 num_dex_files,
1394 key_value_store));
1395 size_oat_header_ += sizeof(OatHeader);
1396 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001397 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001398}
1399
1400size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001401 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1402 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001403 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001404 oat_dex_file.offset_ = offset;
1405 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001406 }
1407 return offset;
1408}
1409
Brian Carlstrom389efb02012-01-11 12:06:26 -08001410size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001411 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001412 InitOatClassesMethodVisitor visitor(this, offset);
1413 bool success = VisitDexMethods(&visitor);
1414 CHECK(success);
1415 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001416
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001417 // Update oat_dex_files_.
1418 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001419 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1420 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001421 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001422 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001424 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001425 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001426 CHECK(oat_class_it == oat_classes_.end());
1427
1428 return offset;
1429}
1430
1431size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001432 InitMapMethodVisitor visitor(this, offset);
1433 bool success = VisitDexMethods(&visitor);
1434 DCHECK(success);
1435 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001436
Brian Carlstrome24fa612011-09-29 00:53:55 -07001437 return offset;
1438}
1439
1440size_t OatWriter::InitOatCode(size_t offset) {
1441 // calculate the offsets within OatHeader to executable code
1442 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001443 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001444 // required to be on a new page boundary
1445 offset = RoundUp(offset, kPageSize);
1446 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001447 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001448 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001449 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001450
Ian Rogers848871b2013-08-05 10:56:33 -07001451 #define DO_TRAMPOLINE(field, fn_name) \
1452 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001453 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1454 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001455 (field) = compiler_driver_->Create ## fn_name(); \
1456 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001457
Ian Rogers848871b2013-08-05 10:56:33 -07001458 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001459 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001460 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001461 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1462 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001463
Ian Rogers848871b2013-08-05 10:56:33 -07001464 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001466 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1467 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1468 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001469 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001470 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001471 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001472 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001473 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001474 return offset;
1475}
1476
1477size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001478 #define VISIT(VisitorType) \
1479 do { \
1480 VisitorType visitor(this, offset); \
1481 bool success = VisitDexMethods(&visitor); \
1482 DCHECK(success); \
1483 offset = visitor.GetOffset(); \
1484 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001485
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001486 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001487 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001488 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001489 }
Logan Chien8b977d32012-02-21 19:14:55 +08001490
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001491 #undef VISIT
1492
Brian Carlstrome24fa612011-09-29 00:53:55 -07001493 return offset;
1494}
1495
David Srbeckybc90fd02015-04-22 19:40:27 +01001496bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001497 CHECK(write_state_ == WriteState::kWriteRoData);
1498
Vladimir Markoe079e212016-05-25 12:49:49 +01001499 // Wrap out to update checksum with each write.
1500 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1501 out = &checksum_updating_out;
1502
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001503 if (!WriteClassOffsets(out)) {
1504 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001505 return false;
1506 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001507
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001508 if (!WriteClasses(out)) {
1509 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001510 return false;
1511 }
1512
Vladimir Markof4da6752014-08-01 19:04:18 +01001513 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001514 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001515 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1516 return false;
1517 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001518 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001519 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001520 relative_offset = WriteMaps(out, file_offset, relative_offset);
1521 if (relative_offset == 0) {
1522 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1523 return false;
1524 }
1525
David Srbeckybc90fd02015-04-22 19:40:27 +01001526 // Write padding.
1527 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1528 relative_offset += size_executable_offset_alignment_;
1529 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1530 size_t expected_file_offset = file_offset + relative_offset;
1531 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1532 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1533 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1534 return 0;
1535 }
1536 DCHECK_OFFSET();
1537
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001538 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001539 return true;
1540}
1541
1542bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001543 CHECK(write_state_ == WriteState::kWriteText);
1544
Vladimir Markoe079e212016-05-25 12:49:49 +01001545 // Wrap out to update checksum with each write.
1546 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1547 out = &checksum_updating_out;
1548
Vladimir Marko944da602016-02-19 12:27:55 +00001549 SetMultiOatRelativePatcherAdjustment();
1550
David Srbeckybc90fd02015-04-22 19:40:27 +01001551 const size_t file_offset = oat_data_offset_;
1552 size_t relative_offset = oat_header_->GetExecutableOffset();
1553 DCHECK_OFFSET();
1554
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001555 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001556 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001557 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001558 return false;
1559 }
1560
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001561 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1562 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001563 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001564 return false;
1565 }
1566
Vladimir Markof4da6752014-08-01 19:04:18 +01001567 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001568 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1570 return false;
1571 }
1572
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001573 if (kIsDebugBuild) {
1574 uint32_t size_total = 0;
1575 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001576 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1577 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001578
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001579 DO_STAT(size_dex_file_alignment_);
1580 DO_STAT(size_executable_offset_alignment_);
1581 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001582 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001583 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001584 DO_STAT(size_interpreter_to_interpreter_bridge_);
1585 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1586 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001587 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001588 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001589 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001590 DO_STAT(size_quick_to_interpreter_bridge_);
1591 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001592 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001593 DO_STAT(size_code_);
1594 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001595 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001596 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001597 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001598 DO_STAT(size_oat_dex_file_location_size_);
1599 DO_STAT(size_oat_dex_file_location_data_);
1600 DO_STAT(size_oat_dex_file_location_checksum_);
1601 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001602 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001603 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001604 DO_STAT(size_oat_lookup_table_alignment_);
1605 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001606 DO_STAT(size_oat_class_offsets_alignment_);
1607 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001608 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001609 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001610 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001611 DO_STAT(size_oat_class_method_offsets_);
1612 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001613
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001614 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001615 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001616 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001617 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001618
Vladimir Markof4da6752014-08-01 19:04:18 +01001619 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001620 CHECK_EQ(size_, relative_offset);
1621
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001622 write_state_ = WriteState::kWriteHeader;
1623 return true;
1624}
1625
1626bool OatWriter::WriteHeader(OutputStream* out,
1627 uint32_t image_file_location_oat_checksum,
1628 uintptr_t image_file_location_oat_begin,
1629 int32_t image_patch_delta) {
1630 CHECK(write_state_ == WriteState::kWriteHeader);
1631
1632 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1633 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1634 if (compiler_driver_->IsBootImage()) {
1635 CHECK_EQ(image_patch_delta, 0);
1636 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1637 } else {
1638 CHECK_ALIGNED(image_patch_delta, kPageSize);
1639 oat_header_->SetImagePatchDelta(image_patch_delta);
1640 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001641 oat_header_->UpdateChecksumWithHeaderData();
1642
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001643 const size_t file_offset = oat_data_offset_;
1644
1645 off_t current_offset = out->Seek(0, kSeekCurrent);
1646 if (current_offset == static_cast<off_t>(-1)) {
1647 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1648 return false;
1649 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001650 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001651 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1652 return false;
1653 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001654 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001655
1656 // Flush all other data before writing the header.
1657 if (!out->Flush()) {
1658 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1659 return false;
1660 }
1661 // Write the header.
1662 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001663 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001664 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1665 return false;
1666 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001667 // Flush the header data.
1668 if (!out->Flush()) {
1669 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001670 return false;
1671 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001672
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001673 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1674 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1675 return false;
1676 }
1677 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1678
1679 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001680 return true;
1681}
1682
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001683bool OatWriter::WriteClassOffsets(OutputStream* out) {
1684 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1685 if (oat_dex_file.class_offsets_offset_ != 0u) {
1686 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1687 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1688 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1689 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1690 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001691 return false;
1692 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001693 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1694 return false;
1695 }
1696 }
1697 }
1698 return true;
1699}
1700
1701bool OatWriter::WriteClasses(OutputStream* out) {
1702 for (OatClass& oat_class : oat_classes_) {
1703 if (!oat_class.Write(this, out, oat_data_offset_)) {
1704 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1705 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001706 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001707 }
1708 return true;
1709}
1710
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001711size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001712 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001713 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1714 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1715 return 0;
1716 }
1717 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001718 size_vmap_table_ = relative_offset - vmap_tables_offset;
1719
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001720 return relative_offset;
1721}
1722
1723size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001724 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001725 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001726
Ian Rogers848871b2013-08-05 10:56:33 -07001727 #define DO_TRAMPOLINE(field) \
1728 do { \
1729 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1730 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001731 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001732 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001733 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001734 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001735 return false; \
1736 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001737 size_ ## field += (field)->size(); \
1738 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001739 DCHECK_OFFSET(); \
1740 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001741
Ian Rogers848871b2013-08-05 10:56:33 -07001742 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001743 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001744 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001745 DO_TRAMPOLINE(quick_resolution_trampoline_);
1746 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1747 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001748 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001749 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001750}
1751
Ian Rogers3d504072014-03-01 09:16:49 -08001752size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001753 const size_t file_offset,
1754 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001755 #define VISIT(VisitorType) \
1756 do { \
1757 VisitorType visitor(this, out, file_offset, relative_offset); \
1758 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1759 return 0; \
1760 } \
1761 relative_offset = visitor.GetOffset(); \
1762 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001763
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001764 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001765
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001766 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001767
Vladimir Markob163bb72015-03-31 21:49:49 +01001768 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1769 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1770 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1771
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001772 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001773}
1774
Vladimir Marko944da602016-02-19 12:27:55 +00001775bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001776 // Get the elf file offset of the oat file.
1777 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1778 if (raw_file_offset == static_cast<off_t>(-1)) {
1779 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1780 return false;
1781 }
1782 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1783 return true;
1784}
1785
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001786bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1787 // Read the dex file header and perform minimal verification.
1788 uint8_t raw_header[sizeof(DexFile::Header)];
1789 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1790 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1791 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1792 return false;
1793 }
1794 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1795 return false;
1796 }
1797
1798 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1799 oat_dex_file->dex_file_size_ = header->file_size_;
1800 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1801 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1802 return true;
1803}
1804
1805bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1806 if (!DexFile::IsMagicValid(raw_header)) {
1807 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1808 return false;
1809 }
1810 if (!DexFile::IsVersionValid(raw_header)) {
1811 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1812 return false;
1813 }
1814 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1815 if (header->file_size_ < sizeof(DexFile::Header)) {
1816 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1817 << " File: " << location;
1818 return false;
1819 }
1820 return true;
1821}
1822
1823bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1824 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1825
1826 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001827 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001828 return false;
1829 }
1830
1831 // Write dex files.
1832 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1833 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1834 return false;
1835 }
1836 }
1837
1838 // Close sources.
1839 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1840 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1841 }
1842 zipped_dex_files_.clear();
1843 zip_archives_.clear();
1844 raw_dex_files_.clear();
1845 return true;
1846}
1847
1848bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1849 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1850 return false;
1851 }
1852 if (oat_dex_file->source_.IsZipEntry()) {
1853 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1854 return false;
1855 }
1856 } else if (oat_dex_file->source_.IsRawFile()) {
1857 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1858 return false;
1859 }
1860 } else {
1861 DCHECK(oat_dex_file->source_.IsRawData());
1862 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1863 return false;
1864 }
1865 }
1866
1867 // Update current size and account for the written data.
1868 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1869 size_ += oat_dex_file->dex_file_size_;
1870 size_dex_file_ += oat_dex_file->dex_file_size_;
1871 return true;
1872}
1873
1874bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1875 // Dex files are required to be 4 byte aligned.
1876 size_t original_offset = size_;
1877 size_t offset = RoundUp(original_offset, 4);
1878 size_dex_file_alignment_ += offset - original_offset;
1879
1880 // Seek to the start of the dex file and flush any pending operations in the stream.
1881 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1882 uint32_t start_offset = oat_data_offset_ + offset;
1883 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1884 if (actual_offset != static_cast<off_t>(start_offset)) {
1885 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1886 << " Expected: " << start_offset
1887 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1888 return false;
1889 }
1890 if (!out->Flush()) {
1891 PLOG(ERROR) << "Failed to flush before writing dex file."
1892 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1893 return false;
1894 }
1895 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1896 if (actual_offset != static_cast<off_t>(start_offset)) {
1897 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1898 << " Expected: " << start_offset
1899 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1900 return false;
1901 }
1902
1903 size_ = offset;
1904 oat_dex_file->dex_file_offset_ = offset;
1905 return true;
1906}
1907
1908bool OatWriter::WriteDexFile(OutputStream* rodata,
1909 File* file,
1910 OatDexFile* oat_dex_file,
1911 ZipEntry* dex_file) {
1912 size_t start_offset = oat_data_offset_ + size_;
1913 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1914
1915 // Extract the dex file and get the extracted size.
1916 std::string error_msg;
1917 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1918 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1919 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1920 return false;
1921 }
1922 if (file->Flush() != 0) {
1923 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1924 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1925 return false;
1926 }
1927 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1928 if (extracted_end == static_cast<off_t>(-1)) {
1929 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1930 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1931 return false;
1932 }
1933 if (extracted_end < static_cast<off_t>(start_offset)) {
1934 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1935 << " Start: " << start_offset
1936 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1937 return false;
1938 }
1939 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1940 if (extracted_size < sizeof(DexFile::Header)) {
1941 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1942 << extracted_size << " File: " << oat_dex_file->GetLocation();
1943 return false;
1944 }
1945
1946 // Read the dex file header and extract required data to OatDexFile.
1947 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1948 if (actual_offset != static_cast<off_t>(start_offset)) {
1949 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1950 << " Expected: " << start_offset
1951 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1952 return false;
1953 }
1954 if (!ReadDexFileHeader(file, oat_dex_file)) {
1955 return false;
1956 }
1957 if (extracted_size < oat_dex_file->dex_file_size_) {
1958 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1959 << " file size from header: " << oat_dex_file->dex_file_size_
1960 << " File: " << oat_dex_file->GetLocation();
1961 return false;
1962 }
1963
1964 // Override the checksum from header with the CRC from ZIP entry.
1965 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1966
1967 // Seek both file and stream to the end offset.
1968 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1969 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1970 if (actual_offset != static_cast<off_t>(end_offset)) {
1971 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1972 << " Expected: " << end_offset
1973 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1974 return false;
1975 }
1976 actual_offset = rodata->Seek(end_offset, kSeekSet);
1977 if (actual_offset != static_cast<off_t>(end_offset)) {
1978 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1979 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1980 return false;
1981 }
1982 if (!rodata->Flush()) {
1983 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1984 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1985 return false;
1986 }
1987
1988 // If we extracted more than the size specified in the header, truncate the file.
1989 if (extracted_size > oat_dex_file->dex_file_size_) {
1990 if (file->SetLength(end_offset) != 0) {
1991 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1992 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1993 return false;
1994 }
1995 }
1996
1997 return true;
1998}
1999
2000bool OatWriter::WriteDexFile(OutputStream* rodata,
2001 File* file,
2002 OatDexFile* oat_dex_file,
2003 File* dex_file) {
2004 size_t start_offset = oat_data_offset_ + size_;
2005 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2006
2007 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2008 if (input_offset != static_cast<off_t>(0)) {
2009 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2010 << " Expected: 0"
2011 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2012 return false;
2013 }
2014 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2015 return false;
2016 }
2017
2018 // Copy the input dex file using sendfile().
2019 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2020 PLOG(ERROR) << "Failed to copy dex file to oat file."
2021 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2022 return false;
2023 }
2024 if (file->Flush() != 0) {
2025 PLOG(ERROR) << "Failed to flush dex file."
2026 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2027 return false;
2028 }
2029
2030 // Check file position and seek the stream to the end offset.
2031 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2032 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2033 if (actual_offset != static_cast<off_t>(end_offset)) {
2034 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2035 << " Expected: " << end_offset
2036 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2037 return false;
2038 }
2039 actual_offset = rodata->Seek(end_offset, kSeekSet);
2040 if (actual_offset != static_cast<off_t>(end_offset)) {
2041 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2042 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2043 return false;
2044 }
2045 if (!rodata->Flush()) {
2046 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2047 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2048 return false;
2049 }
2050
2051 return true;
2052}
2053
2054bool OatWriter::WriteDexFile(OutputStream* rodata,
2055 OatDexFile* oat_dex_file,
2056 const uint8_t* dex_file) {
2057 // Note: The raw data has already been checked to contain the header
2058 // and all the data that the header specifies as the file size.
2059 DCHECK(dex_file != nullptr);
2060 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2061 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2062
Vladimir Markoe079e212016-05-25 12:49:49 +01002063 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002064 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2065 << " to " << rodata->GetLocation();
2066 return false;
2067 }
2068 if (!rodata->Flush()) {
2069 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2070 << " File: " << oat_dex_file->GetLocation();
2071 return false;
2072 }
2073
2074 // Update dex file size and resize class offsets in the OatDexFile.
2075 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2076 oat_dex_file->dex_file_size_ = header->file_size_;
2077 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2078 return true;
2079}
2080
2081bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2082 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2083
2084 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2085 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2086 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2087 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2088 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2089 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2090 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2091 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2092 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2093 return false;
2094 }
2095
2096 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2097 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2098
2099 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2100 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2101
2102 // Write OatDexFile.
2103 if (!oat_dex_file->Write(this, rodata)) {
2104 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2105 return false;
2106 }
2107 }
2108
2109 return true;
2110}
2111
2112bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2113 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2114
2115 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2116 if (file->SetLength(new_length) != 0) {
2117 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2118 << "File: " << file->GetPath();
2119 return false;
2120 }
2121 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2122 if (actual_offset != static_cast<off_t>(new_length)) {
2123 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2124 << " Actual: " << actual_offset << " Expected: " << new_length
2125 << " File: " << rodata->GetLocation();
2126 return false;
2127 }
2128 if (!rodata->Flush()) {
2129 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2130 << " File: " << rodata->GetLocation();
2131 return false;
2132 }
2133 return true;
2134}
2135
2136bool OatWriter::OpenDexFiles(
2137 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002138 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002139 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2140 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2141 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2142
2143 if (oat_dex_files_.empty()) {
2144 // Nothing to do.
2145 return true;
2146 }
2147
2148 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2149 size_t length = size_ - map_offset;
2150 std::string error_msg;
2151 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2152 PROT_READ | PROT_WRITE,
2153 MAP_SHARED,
2154 file->Fd(),
2155 oat_data_offset_ + map_offset,
2156 /* low_4gb */ false,
2157 file->GetPath().c_str(),
2158 &error_msg));
2159 if (dex_files_map == nullptr) {
2160 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2161 << " error: " << error_msg;
2162 return false;
2163 }
2164 std::vector<std::unique_ptr<const DexFile>> dex_files;
2165 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2166 // Make sure no one messed with input files while we were copying data.
2167 // At the very least we need consistent file size and number of class definitions.
2168 const uint8_t* raw_dex_file =
2169 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2170 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2171 // Note: ValidateDexFileHeader() already logged an error message.
2172 LOG(ERROR) << "Failed to verify written dex file header!"
2173 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2174 << " ~ " << static_cast<const void*>(raw_dex_file);
2175 return false;
2176 }
2177 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2178 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2179 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2180 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2181 << " Output: " << file->GetPath();
2182 return false;
2183 }
2184 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2185 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2186 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2187 << " Output: " << file->GetPath();
2188 return false;
2189 }
2190
2191 // Now, open the dex file.
2192 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2193 oat_dex_file.dex_file_size_,
2194 oat_dex_file.GetLocation(),
2195 oat_dex_file.dex_file_location_checksum_,
2196 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002197 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002198 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002199 &error_msg));
2200 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002201 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2202 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002203 return false;
2204 }
2205 }
2206
2207 *opened_dex_files_map = std::move(dex_files_map);
2208 *opened_dex_files = std::move(dex_files);
2209 return true;
2210}
2211
2212bool OatWriter::WriteTypeLookupTables(
2213 MemMap* opened_dex_files_map,
2214 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2215 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2216
2217 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2218 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2219 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2220 if (oat_dex_file->lookup_table_offset_ != 0u) {
2221 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2222 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2223 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2224 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2225 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2226 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2227 }
2228 }
2229
2230 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2231 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2232 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2233 return false;
2234 }
2235
2236 return true;
2237}
2238
Vladimir Markof4da6752014-08-01 19:04:18 +01002239bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2240 static const uint8_t kPadding[] = {
2241 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2242 };
2243 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002244 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002245 return false;
2246 }
2247 size_code_alignment_ += aligned_code_delta;
2248 return true;
2249}
2250
Vladimir Marko944da602016-02-19 12:27:55 +00002251void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2252 DCHECK(dex_files_ != nullptr);
2253 DCHECK(relative_patcher_ != nullptr);
2254 DCHECK_NE(oat_data_offset_, 0u);
2255 if (image_writer_ != nullptr && !dex_files_->empty()) {
2256 // The oat data begin may not be initialized yet but the oat file offset is ready.
2257 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2258 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2259 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002260 }
2261}
2262
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002263OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2264 DexFileSource source,
2265 CreateTypeLookupTable create_type_lookup_table)
2266 : source_(source),
2267 create_type_lookup_table_(create_type_lookup_table),
2268 dex_file_size_(0),
2269 offset_(0),
2270 dex_file_location_size_(strlen(dex_file_location)),
2271 dex_file_location_data_(dex_file_location),
2272 dex_file_location_checksum_(0u),
2273 dex_file_offset_(0u),
2274 class_offsets_offset_(0u),
2275 lookup_table_offset_(0u),
2276 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002277}
2278
2279size_t OatWriter::OatDexFile::SizeOf() const {
2280 return sizeof(dex_file_location_size_)
2281 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002282 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002283 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002284 + sizeof(class_offsets_offset_)
2285 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002286}
2287
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002288void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2289 DCHECK_EQ(lookup_table_offset_, 0u);
2290 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2291 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2292 if (table_size != 0u) {
2293 // Type tables are required to be 4 byte aligned.
2294 size_t original_offset = oat_writer->size_;
2295 size_t offset = RoundUp(original_offset, 4);
2296 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2297 lookup_table_offset_ = offset;
2298 oat_writer->size_ = offset + table_size;
2299 oat_writer->size_oat_lookup_table_ += table_size;
2300 }
2301 }
2302}
2303
2304void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2305 DCHECK_EQ(class_offsets_offset_, 0u);
2306 if (!class_offsets_.empty()) {
2307 // Class offsets are required to be 4 byte aligned.
2308 size_t original_offset = oat_writer->size_;
2309 size_t offset = RoundUp(original_offset, 4);
2310 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2311 class_offsets_offset_ = offset;
2312 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2313 }
2314}
2315
2316bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2317 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002318 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002319
Vladimir Markoe079e212016-05-25 12:49:49 +01002320 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002321 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002322 return false;
2323 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002324 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002325
Vladimir Markoe079e212016-05-25 12:49:49 +01002326 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002327 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002328 return false;
2329 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002330 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002331
Vladimir Markoe079e212016-05-25 12:49:49 +01002332 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002333 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002334 return false;
2335 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002336 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002337
Vladimir Markoe079e212016-05-25 12:49:49 +01002338 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002339 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002340 return false;
2341 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002342 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002343
Vladimir Markoe079e212016-05-25 12:49:49 +01002344 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2346 return false;
2347 }
2348 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2349
Vladimir Markoe079e212016-05-25 12:49:49 +01002350 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002351 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2352 return false;
2353 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002354 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002355
2356 return true;
2357}
2358
2359bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002360 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002361 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2362 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002363 return false;
2364 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002365 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002366 return true;
2367}
2368
Brian Carlstromba150c32013-08-27 17:31:03 -07002369OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002370 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002371 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002372 mirror::Class::Status status)
2373 : compiled_methods_(compiled_methods) {
2374 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002375 CHECK_LE(num_non_null_compiled_methods, num_methods);
2376
Brian Carlstrom265091e2013-01-30 14:08:26 -08002377 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002378 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2379
2380 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2381 // apply when there are 0 methods, we just arbitrarily say that 0
2382 // methods means kOatClassNoneCompiled and that we won't use
2383 // kOatClassAllCompiled unless there is at least one compiled
2384 // method. This means in an interpretter only system, we can assert
2385 // that all classes are kOatClassNoneCompiled.
2386 if (num_non_null_compiled_methods == 0) {
2387 type_ = kOatClassNoneCompiled;
2388 } else if (num_non_null_compiled_methods == num_methods) {
2389 type_ = kOatClassAllCompiled;
2390 } else {
2391 type_ = kOatClassSomeCompiled;
2392 }
2393
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002394 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002395 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002396 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002397
2398 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2399 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002400 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002401 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2402 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2403 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2404 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002405 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002406 method_bitmap_size_ = 0;
2407 }
2408
2409 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002410 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002411 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002412 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2413 } else {
2414 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2415 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2416 if (type_ == kOatClassSomeCompiled) {
2417 method_bitmap_->SetBit(i);
2418 }
2419 }
2420 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002421}
2422
Brian Carlstrom265091e2013-01-30 14:08:26 -08002423size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2424 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002425 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2426 if (method_offset == 0) {
2427 return 0;
2428 }
2429 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002430}
2431
2432size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2433 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002434 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002435}
2436
2437size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002438 return sizeof(status_)
2439 + sizeof(type_)
2440 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2441 + method_bitmap_size_
2442 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002443}
2444
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002445bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002446 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002447 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002448 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002449 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002450 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002451 return false;
2452 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002453 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002454
Vladimir Markoe079e212016-05-25 12:49:49 +01002455 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002456 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002457 return false;
2458 }
2459 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002460
Brian Carlstromba150c32013-08-27 17:31:03 -07002461 if (method_bitmap_size_ != 0) {
2462 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002463 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002464 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002465 return false;
2466 }
2467 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002468
Vladimir Markoe079e212016-05-25 12:49:49 +01002469 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002470 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002471 return false;
2472 }
2473 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2474 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002475
Vladimir Markoe079e212016-05-25 12:49:49 +01002476 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002477 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002478 return false;
2479 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002480 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002481 return true;
2482}
2483
Brian Carlstrome24fa612011-09-29 00:53:55 -07002484} // namespace art