blob: 20956087ba94ffac20669b5b39782d1a45ab650e [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000027#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070030#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070031#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000032#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000033#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "dex_file-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000036#include "driver/compiler_driver.h"
37#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010038#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030040#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010041#include "image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000042#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000043#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/array.h"
45#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010046#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070047#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010048#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070049#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070050#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070051#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030052#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010053#include "utils/dex_cache_arrays_layout-inl.h"
jeffhaoec014232012-09-05 10:42:25 -070054#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000055#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070056
57namespace art {
58
Vladimir Marko9bdf1082016-01-21 12:15:52 +000059namespace { // anonymous namespace
60
61typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
62
63const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
64 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
65}
66
Vladimir Markoe079e212016-05-25 12:49:49 +010067class ChecksumUpdatingOutputStream : public OutputStream {
68 public:
69 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
70 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
71
72 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
73 oat_header_->UpdateChecksum(buffer, byte_count);
74 return out_->WriteFully(buffer, byte_count);
75 }
76
77 off_t Seek(off_t offset, Whence whence) OVERRIDE {
78 return out_->Seek(offset, whence);
79 }
80
81 bool Flush() OVERRIDE {
82 return out_->Flush();
83 }
84
85 private:
86 OutputStream* const out_;
87 OatHeader* const oat_header_;
88};
89
Vladimir Marko0c737df2016-08-01 16:33:16 +010090inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
91 // We want to align the code rather than the preheader.
92 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
93 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
94 return aligned_code_offset - unaligned_code_offset;
95}
96
Vladimir Marko9bdf1082016-01-21 12:15:52 +000097} // anonymous namespace
98
99// Defines the location of the raw dex file to write.
100class OatWriter::DexFileSource {
101 public:
102 explicit DexFileSource(ZipEntry* zip_entry)
103 : type_(kZipEntry), source_(zip_entry) {
104 DCHECK(source_ != nullptr);
105 }
106
107 explicit DexFileSource(File* raw_file)
108 : type_(kRawFile), source_(raw_file) {
109 DCHECK(source_ != nullptr);
110 }
111
112 explicit DexFileSource(const uint8_t* dex_file)
113 : type_(kRawData), source_(dex_file) {
114 DCHECK(source_ != nullptr);
115 }
116
117 bool IsZipEntry() const { return type_ == kZipEntry; }
118 bool IsRawFile() const { return type_ == kRawFile; }
119 bool IsRawData() const { return type_ == kRawData; }
120
121 ZipEntry* GetZipEntry() const {
122 DCHECK(IsZipEntry());
123 DCHECK(source_ != nullptr);
124 return static_cast<ZipEntry*>(const_cast<void*>(source_));
125 }
126
127 File* GetRawFile() const {
128 DCHECK(IsRawFile());
129 DCHECK(source_ != nullptr);
130 return static_cast<File*>(const_cast<void*>(source_));
131 }
132
133 const uint8_t* GetRawData() const {
134 DCHECK(IsRawData());
135 DCHECK(source_ != nullptr);
136 return static_cast<const uint8_t*>(source_);
137 }
138
139 void Clear() {
140 type_ = kNone;
141 source_ = nullptr;
142 }
143
144 private:
145 enum Type {
146 kNone,
147 kZipEntry,
148 kRawFile,
149 kRawData,
150 };
151
152 Type type_;
153 const void* source_;
154};
155
Vladimir Marko49b0f452015-12-10 13:49:19 +0000156class OatWriter::OatClass {
157 public:
158 OatClass(size_t offset,
159 const dchecked_vector<CompiledMethod*>& compiled_methods,
160 uint32_t num_non_null_compiled_methods,
161 mirror::Class::Status status);
162 OatClass(OatClass&& src) = default;
163 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
164 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
165 size_t SizeOf() const;
166 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
167
168 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
169 return compiled_methods_[class_def_method_index];
170 }
171
172 // Offset of start of OatClass from beginning of OatHeader. It is
173 // used to validate file position when writing.
174 size_t offset_;
175
176 // CompiledMethods for each class_def_method_index, or null if no method is available.
177 dchecked_vector<CompiledMethod*> compiled_methods_;
178
179 // Offset from OatClass::offset_ to the OatMethodOffsets for the
180 // class_def_method_index. If 0, it means the corresponding
181 // CompiledMethod entry in OatClass::compiled_methods_ should be
182 // null and that the OatClass::type_ should be kOatClassBitmap.
183 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
184
185 // Data to write.
186
187 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
188 int16_t status_;
189
190 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
191 uint16_t type_;
192
193 uint32_t method_bitmap_size_;
194
195 // bit vector indexed by ClassDef method index. When
196 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
197 // method has an OatMethodOffsets in methods_offsets_, otherwise
198 // the entry was ommited to save space. If OatClassType::type_ is
199 // not is kOatClassBitmap, the bitmap will be null.
200 std::unique_ptr<BitVector> method_bitmap_;
201
202 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
203 // present in the OatClass. Note that some may be missing if
204 // OatClass::compiled_methods_ contains null values (and
205 // oat_method_offsets_offsets_from_oat_class_ should contain 0
206 // values in this case).
207 dchecked_vector<OatMethodOffsets> method_offsets_;
208 dchecked_vector<OatQuickMethodHeader> method_headers_;
209
210 private:
211 size_t GetMethodOffsetsRawSize() const {
212 return method_offsets_.size() * sizeof(method_offsets_[0]);
213 }
214
215 DISALLOW_COPY_AND_ASSIGN(OatClass);
216};
217
218class OatWriter::OatDexFile {
219 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000220 OatDexFile(const char* dex_file_location,
221 DexFileSource source,
222 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000223 OatDexFile(OatDexFile&& src) = default;
224
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 const char* GetLocation() const {
226 return dex_file_location_data_;
227 }
228
David Brazdilb92ba622016-09-01 16:00:30 +0000229 void ReserveTypeLookupTable(OatWriter* oat_writer);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000230 void ReserveClassOffsets(OatWriter* oat_writer);
231
Vladimir Marko49b0f452015-12-10 13:49:19 +0000232 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000233 bool Write(OatWriter* oat_writer, OutputStream* out) const;
234 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
235
236 // The source of the dex file.
237 DexFileSource source_;
238
239 // Whether to create the type lookup table.
240 CreateTypeLookupTable create_type_lookup_table_;
241
242 // Dex file size. Initialized when writing the dex file.
243 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000244
245 // Offset of start of OatDexFile from beginning of OatHeader. It is
246 // used to validate file position when writing.
247 size_t offset_;
248
249 // Data to write.
250 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000251 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000252 uint32_t dex_file_location_checksum_;
253 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000254 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000255 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000256
257 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000258 dchecked_vector<uint32_t> class_offsets_;
259
260 private:
261 size_t GetClassOffsetsRawSize() const {
262 return class_offsets_.size() * sizeof(class_offsets_[0]);
263 }
264
265 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
266};
267
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100268#define DCHECK_OFFSET() \
269 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
270 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
271
272#define DCHECK_OFFSET_() \
273 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
274 << "file_offset=" << file_offset << " offset_=" << offset_
275
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000276OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
277 : write_state_(WriteState::kAddingDexFileSources),
278 timings_(timings),
279 raw_dex_files_(),
280 zip_archives_(),
281 zipped_dex_files_(),
282 zipped_dex_file_locations_(),
283 compiler_driver_(nullptr),
284 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800285 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000286 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100287 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000288 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100289 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700290 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700291 size_dex_file_alignment_(0),
292 size_executable_offset_alignment_(0),
293 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700294 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700295 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700296 size_interpreter_to_interpreter_bridge_(0),
297 size_interpreter_to_compiled_code_bridge_(0),
298 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800299 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700300 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700301 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700302 size_quick_to_interpreter_bridge_(0),
303 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100304 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700305 size_code_(0),
306 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100307 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100308 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700310 size_oat_dex_file_location_size_(0),
311 size_oat_dex_file_location_data_(0),
312 size_oat_dex_file_location_checksum_(0),
313 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000314 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000315 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000316 size_oat_lookup_table_alignment_(0),
317 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000318 size_oat_class_offsets_alignment_(0),
319 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700320 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700321 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700322 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100323 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000324 relative_patcher_(nullptr),
325 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000326}
327
328bool OatWriter::AddDexFileSource(const char* filename,
329 const char* location,
330 CreateTypeLookupTable create_type_lookup_table) {
331 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
332 uint32_t magic;
333 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700334 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
335 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000336 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
337 return false;
338 } else if (IsDexMagic(magic)) {
339 // The file is open for reading, not writing, so it's OK to let the File destructor
340 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700341 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000342 oat_dex_files_.emplace_back(location,
343 DexFileSource(raw_dex_files_.back().get()),
344 create_type_lookup_table);
345 } else if (IsZipMagic(magic)) {
346 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
347 return false;
348 }
349 } else {
350 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
351 return false;
352 }
353 return true;
354}
355
356// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700357bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000358 const char* location,
359 CreateTypeLookupTable create_type_lookup_table) {
360 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
361 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700362 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000363 ZipArchive* zip_archive = zip_archives_.back().get();
364 if (zip_archive == nullptr) {
365 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
366 << error_msg;
367 return false;
368 }
369 for (size_t i = 0; ; ++i) {
370 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
371 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
372 if (entry == nullptr) {
373 break;
374 }
375 zipped_dex_files_.push_back(std::move(entry));
376 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
377 const char* full_location = zipped_dex_file_locations_.back().c_str();
378 oat_dex_files_.emplace_back(full_location,
379 DexFileSource(zipped_dex_files_.back().get()),
380 create_type_lookup_table);
381 }
382 if (zipped_dex_file_locations_.empty()) {
383 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
384 return false;
385 }
386 return true;
387}
388
389// Add dex file source from raw memory.
390bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
391 const char* location,
392 uint32_t location_checksum,
393 CreateTypeLookupTable create_type_lookup_table) {
394 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
395 if (data.size() < sizeof(DexFile::Header)) {
396 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
397 << data.size() << " File: " << location;
398 return false;
399 }
400 if (!ValidateDexFileHeader(data.data(), location)) {
401 return false;
402 }
403 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
404 if (data.size() < header->file_size_) {
405 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
406 << " file size from header: " << header->file_size_ << " File: " << location;
407 return false;
408 }
409
410 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
411 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
412 return true;
413}
414
415dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
416 dchecked_vector<const char*> locations;
417 locations.reserve(oat_dex_files_.size());
418 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
419 locations.push_back(oat_dex_file.GetLocation());
420 }
421 return locations;
422}
423
424bool OatWriter::WriteAndOpenDexFiles(
425 OutputStream* rodata,
426 File* file,
427 InstructionSet instruction_set,
428 const InstructionSetFeatures* instruction_set_features,
429 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800430 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000431 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
432 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
433 CHECK(write_state_ == WriteState::kAddingDexFileSources);
434
435 size_t offset = InitOatHeader(instruction_set,
436 instruction_set_features,
437 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
438 key_value_store);
David Brazdilb92ba622016-09-01 16:00:30 +0000439 offset = InitOatDexFiles(offset);
440 size_ = offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000441
442 std::unique_ptr<MemMap> dex_files_map;
443 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdilb92ba622016-09-01 16:00:30 +0000444 if (!WriteDexFiles(rodata, file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000445 return false;
446 }
David Brazdilb92ba622016-09-01 16:00:30 +0000447 // Reserve space for type lookup tables and update type_lookup_table_offset_.
448 for (OatDexFile& oat_dex_file : oat_dex_files_) {
449 oat_dex_file.ReserveTypeLookupTable(this);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000450 }
David Brazdilb92ba622016-09-01 16:00:30 +0000451 size_t size_after_type_lookup_tables = size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 // Reserve space for class offsets and update class_offsets_offset_.
453 for (OatDexFile& oat_dex_file : oat_dex_files_) {
454 oat_dex_file.ReserveClassOffsets(this);
455 }
David Brazdilb92ba622016-09-01 16:00:30 +0000456 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
457 if (!WriteOatDexFiles(&checksum_updating_rodata) ||
458 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
459 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
460 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
David Brazdil1a069a52016-08-31 17:15:12 +0100461 return false;
Vladimir Markoe079e212016-05-25 12:49:49 +0100462 }
463
David Brazdilb92ba622016-09-01 16:00:30 +0000464 // Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
465 // piece would be difficult because we're not using the OutpuStream directly.
466 if (!oat_dex_files_.empty()) {
467 size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
468 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
469 }
470
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000471 *opened_dex_files_map = std::move(dex_files_map);
472 *opened_dex_files = std::move(dex_files);
473 write_state_ = WriteState::kPrepareLayout;
474 return true;
475}
476
477void OatWriter::PrepareLayout(const CompilerDriver* compiler,
478 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000479 const std::vector<const DexFile*>& dex_files,
480 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 CHECK(write_state_ == WriteState::kPrepareLayout);
482
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000483 compiler_driver_ = compiler;
484 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000485 dex_files_ = &dex_files;
486 relative_patcher_ = relative_patcher;
487 SetMultiOatRelativePatcherAdjustment();
488
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 if (compiling_boot_image_) {
490 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800491 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100492 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100494
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800496 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800498 offset = InitOatClasses(offset);
499 }
500 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000501 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100502 offset = InitOatMaps(offset);
503 }
504 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000505 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800506 offset = InitOatCode(offset);
507 }
508 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000509 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800510 offset = InitOatCodeDexFiles(offset);
511 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700512 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700513
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800514 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100515 // Allocate space for app dex cache arrays in the .bss section.
516 size_t bss_start = RoundUp(size_, kPageSize);
Andreas Gampe542451c2016-07-26 09:02:02 -0700517 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100518 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000519 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100520 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
521 DexCacheArraysLayout layout(pointer_size, dex_file);
522 bss_size_ += layout.Size();
523 }
524 }
525
Brian Carlstrome24fa612011-09-29 00:53:55 -0700526 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800527 if (compiling_boot_image_) {
528 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000529 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800530 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000531
532 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700533}
534
Ian Rogers0571d352011-11-03 19:51:38 -0700535OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700536}
537
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100538class OatWriter::DexMethodVisitor {
539 public:
540 DexMethodVisitor(OatWriter* writer, size_t offset)
541 : writer_(writer),
542 offset_(offset),
543 dex_file_(nullptr),
544 class_def_index_(DexFile::kDexNoIndex) {
545 }
546
547 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
548 DCHECK(dex_file_ == nullptr);
549 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
550 dex_file_ = dex_file;
551 class_def_index_ = class_def_index;
552 return true;
553 }
554
555 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
556
557 virtual bool EndClass() {
558 if (kIsDebugBuild) {
559 dex_file_ = nullptr;
560 class_def_index_ = DexFile::kDexNoIndex;
561 }
562 return true;
563 }
564
565 size_t GetOffset() const {
566 return offset_;
567 }
568
569 protected:
570 virtual ~DexMethodVisitor() { }
571
572 OatWriter* const writer_;
573
574 // The offset is usually advanced for each visited method by the derived class.
575 size_t offset_;
576
577 // The dex file and class def index are set in StartClass().
578 const DexFile* dex_file_;
579 size_t class_def_index_;
580};
581
582class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
583 public:
584 OatDexMethodVisitor(OatWriter* writer, size_t offset)
585 : DexMethodVisitor(writer, offset),
586 oat_class_index_(0u),
587 method_offsets_index_(0u) {
588 }
589
590 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
591 DexMethodVisitor::StartClass(dex_file, class_def_index);
592 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
593 method_offsets_index_ = 0u;
594 return true;
595 }
596
597 bool EndClass() {
598 ++oat_class_index_;
599 return DexMethodVisitor::EndClass();
600 }
601
602 protected:
603 size_t oat_class_index_;
604 size_t method_offsets_index_;
605};
606
607class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
608 public:
609 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
610 : DexMethodVisitor(writer, offset),
611 compiled_methods_(),
612 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000613 size_t num_classes = 0u;
614 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
615 num_classes += oat_dex_file.class_offsets_.size();
616 }
617 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100618 compiled_methods_.reserve(256u);
619 }
620
621 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
622 DexMethodVisitor::StartClass(dex_file, class_def_index);
623 compiled_methods_.clear();
624 num_non_null_compiled_methods_ = 0u;
625 return true;
626 }
627
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300628 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
629 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100630 // Fill in the compiled_methods_ array for methods that have a
631 // CompiledMethod. We track the number of non-null entries in
632 // num_non_null_compiled_methods_ since we only want to allocate
633 // OatMethodOffsets for the compiled methods.
634 uint32_t method_idx = it.GetMemberIndex();
635 CompiledMethod* compiled_method =
636 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
637 compiled_methods_.push_back(compiled_method);
638 if (compiled_method != nullptr) {
639 ++num_non_null_compiled_methods_;
640 }
641 return true;
642 }
643
644 bool EndClass() {
645 ClassReference class_ref(dex_file_, class_def_index_);
646 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
647 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700648 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100649 status = compiled_class->GetStatus();
650 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
651 status = mirror::Class::kStatusError;
652 } else {
653 status = mirror::Class::kStatusNotReady;
654 }
655
Vladimir Marko49b0f452015-12-10 13:49:19 +0000656 writer_->oat_classes_.emplace_back(offset_,
657 compiled_methods_,
658 num_non_null_compiled_methods_,
659 status);
660 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100661 return DexMethodVisitor::EndClass();
662 }
663
664 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000665 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100666 size_t num_non_null_compiled_methods_;
667};
668
669class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
670 public:
671 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100672 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100673 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100674 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100675 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
676 }
677
678 bool EndClass() {
679 OatDexMethodVisitor::EndClass();
680 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100681 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100682 }
683 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100684 }
685
686 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700687 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000688 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100689 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
690
691 if (compiled_method != nullptr) {
692 // Derived from CompiledMethod.
693 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100694
Vladimir Marko35831e82015-09-11 11:59:18 +0100695 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
696 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800697 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800698
David Srbecky009e2a62015-04-15 02:46:30 +0100699 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100700 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800701 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000702 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000703 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
704 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800705 // Duplicate methods, we want the same code for both of them so that the oat writer puts
706 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800707 } else {
708 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100709 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800710 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000711 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100712 quick_code_offset = dedupe_map_.GetOrCreate(
713 compiled_method,
714 [this, &deduped, compiled_method, &it, thumb_offset]() {
715 deduped = false;
716 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
717 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800718 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100719
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100720 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000721 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100722 // TODO: Should this be a hard failure?
723 LOG(WARNING) << "Multiple definitions of "
724 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000725 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
726 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100727 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000728 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100729 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800730 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100731
Elliott Hughes956af0f2014-12-11 14:34:28 -0800732 // Update quick method header.
733 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
734 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800735 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100736 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
737 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100738 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800739 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
740 // to 0-offset and we need to adjust it by code_offset.
741 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100742 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800743 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100744 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800745 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800746 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
747 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
748 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100749 *method_header = OatQuickMethodHeader(vmap_table_offset,
750 frame_size_in_bytes,
751 core_spill_mask,
752 fp_spill_mask,
753 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100754
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000755 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800756 // Update offsets. (Checksum is updated when writing.)
757 offset_ += sizeof(*method_header); // Method header is prepended before code.
758 offset_ += code_size;
759 // Record absolute patch locations.
760 if (!compiled_method->GetPatches().empty()) {
761 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
762 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000763 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100764 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100765 }
766 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100767 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800768 }
Alex Light78382fa2014-06-06 15:45:32 -0700769
David Srbecky91cc06c2016-03-07 16:13:58 +0000770 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000771 // Exclude quickened dex methods (code_size == 0) since they have no native code.
772 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
773 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800774 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000775 debug::MethodDebugInfo info = debug::MethodDebugInfo();
776 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000777 info.dex_file = dex_file_;
778 info.class_def_index = class_def_index_;
779 info.dex_method_index = it.GetMemberIndex();
780 info.access_flags = it.GetMethodAccessFlags();
781 info.code_item = it.GetMethodCodeItem();
782 info.isa = compiled_method->GetInstructionSet();
783 info.deduped = deduped;
784 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
785 info.is_optimized = method_header->IsOptimized();
786 info.is_code_address_text_relative = true;
787 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
788 info.code_size = code_size;
789 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
790 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
791 info.cfi = compiled_method->GetCFIInfo();
792 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100793 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100795 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
796 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
797 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100798 ++method_offsets_index_;
799 }
800
801 return true;
802 }
803
804 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000805 struct CodeOffsetsKeyComparator {
806 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100807 // Code is deduplicated by CompilerDriver, compare only data pointers.
808 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
809 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000810 }
811 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100812 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
813 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000814 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100815 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
816 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000817 }
818 return false;
819 }
820 };
821
David Srbecky009e2a62015-04-15 02:46:30 +0100822 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
823 const ClassDataItemIterator& it,
824 uint32_t thumb_offset) {
825 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100826 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100827 offset_ += CodeAlignmentSize(offset_, *compiled_method);
828 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100829 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
830 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
831 }
832
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833 // Deduplication is already done on a pointer basis by the compiler driver,
834 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100835 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100836
David Srbecky009e2a62015-04-15 02:46:30 +0100837 // Cache of compiler's --debuggable option.
838 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100839};
840
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
842 public:
843 InitMapMethodVisitor(OatWriter* writer, size_t offset)
844 : OatDexMethodVisitor(writer, offset) {
845 }
846
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700847 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700848 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000849 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100850 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
851
852 if (compiled_method != nullptr) {
853 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100854 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100855
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100856 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100857 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100858 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100859 size_t offset = dedupe_map_.GetOrCreate(
860 map.data(),
861 [this, map_size]() {
862 uint32_t new_offset = offset_;
863 offset_ += map_size;
864 return new_offset;
865 });
866 // Code offset is not initialized yet, so set the map offset to 0u-offset.
867 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
868 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100869 }
870 ++method_offsets_index_;
871 }
872
873 return true;
874 }
875
876 private:
877 // Deduplication is already done on a pointer basis by the compiler driver,
878 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100879 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100880};
881
882class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
883 public:
884 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800885 : OatDexMethodVisitor(writer, offset),
886 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100887 }
888
889 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700890 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800891 const DexFile::TypeId& type_id =
892 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
893 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
894 // Skip methods that are not in the image.
895 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
896 return true;
897 }
898
Vladimir Marko49b0f452015-12-10 13:49:19 +0000899 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100900 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
901
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800902 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 if (compiled_method != nullptr) {
904 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
905 offsets = oat_class->method_offsets_[method_offsets_index_];
906 ++method_offsets_index_;
907 }
908
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100909 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100910 // Unchecked as we hold mutator_lock_ on entry.
911 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800912 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700913 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
914 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800915 ArtMethod* method;
916 if (writer_->HasBootImage()) {
917 const InvokeType invoke_type = it.GetMethodInvokeType(
918 dex_file_->GetClassDef(class_def_index_));
919 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
920 *dex_file_,
921 it.GetMemberIndex(),
922 dex_cache,
923 ScopedNullHandle<mirror::ClassLoader>(),
924 nullptr,
925 invoke_type);
926 if (method == nullptr) {
927 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
928 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
929 soa.Self()->AssertPendingException();
930 mirror::Throwable* exc = soa.Self()->GetException();
931 std::string dump = exc->Dump();
932 LOG(FATAL) << dump;
933 UNREACHABLE();
934 }
935 } else {
936 // Should already have been resolved by the compiler, just peek into the dex cache.
937 // It may not be resolved if the class failed to verify, in this case, don't set the
938 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
939 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700940 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800941 if (method != nullptr &&
942 compiled_method != nullptr &&
943 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100944 method->SetEntryPointFromQuickCompiledCodePtrSize(
945 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
946 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100947
948 return true;
949 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800950
951 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -0700952 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100953};
954
955class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
956 public:
957 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100958 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 : OatDexMethodVisitor(writer, relative_offset),
960 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100961 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100962 soa_(Thread::Current()),
963 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100964 class_linker_(Runtime::Current()->GetClassLinker()),
965 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100966 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800967 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100968 // If we're creating the image, the address space must be ready so that we can apply patches.
969 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100970 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100971 }
972
Vladimir Markof4da6752014-08-01 19:04:18 +0100973 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100974 }
975
976 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700977 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100978 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
979 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700980 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000981 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100982 }
983 return true;
984 }
985
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700986 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100987 bool result = OatDexMethodVisitor::EndClass();
988 if (oat_class_index_ == writer_->oat_classes_.size()) {
989 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000990 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100991 if (UNLIKELY(offset_ == 0u)) {
992 PLOG(ERROR) << "Failed to write final relative call thunks";
993 result = false;
994 }
995 }
996 return result;
997 }
998
999 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001000 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001001 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001002 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1003
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001004 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1005 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001006 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001007 size_t file_offset = file_offset_;
1008 OutputStream* out = out_;
1009
Vladimir Marko35831e82015-09-11 11:59:18 +01001010 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1011 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001012
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001013 // Deduplicate code arrays.
1014 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1015 if (method_offsets.code_offset_ > offset_) {
1016 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1017 if (offset_ == 0u) {
1018 ReportWriteFailure("relative call thunk", it);
1019 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001020 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001021 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1022 if (alignment_size != 0) {
1023 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001024 ReportWriteFailure("code alignment padding", it);
1025 return false;
1026 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001027 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001028 DCHECK_OFFSET_();
1029 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001030 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001031 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1032 DCHECK_EQ(method_offsets.code_offset_,
1033 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1034 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1035 const OatQuickMethodHeader& method_header =
1036 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001037 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001038 ReportWriteFailure("method header", it);
1039 return false;
1040 }
1041 writer_->size_method_header_ += sizeof(method_header);
1042 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001043 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001044
1045 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001046 patched_code_.assign(quick_code.begin(), quick_code.end());
1047 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001048 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001049 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001050 switch (patch.GetType()) {
1051 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001052 // NOTE: Relative calls across oat files are not supported.
1053 uint32_t target_offset = GetTargetOffset(patch);
1054 writer_->relative_patcher_->PatchCall(&patched_code_,
1055 literal_offset,
1056 offset_ + literal_offset,
1057 target_offset);
1058 break;
1059 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001060 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001061 uint32_t target_offset = GetDexCacheOffset(patch);
1062 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1063 patch,
1064 offset_ + literal_offset,
1065 target_offset);
1066 break;
1067 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001068 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001069 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1070 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1071 patch,
1072 offset_ + literal_offset,
1073 target_offset);
1074 break;
1075 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001076 case LinkerPatch::Type::kTypeRelative: {
1077 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1078 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1079 patch,
1080 offset_ + literal_offset,
1081 target_offset);
1082 break;
1083 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001084 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001085 uint32_t target_offset = GetTargetOffset(patch);
1086 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1087 break;
1088 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001089 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001090 ArtMethod* method = GetTargetMethod(patch);
1091 PatchMethodAddress(&patched_code_, literal_offset, method);
1092 break;
1093 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001094 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001095 mirror::String* string = GetTargetString(patch);
1096 PatchObjectAddress(&patched_code_, literal_offset, string);
1097 break;
1098 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001099 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001100 mirror::Class* type = GetTargetType(patch);
1101 PatchObjectAddress(&patched_code_, literal_offset, type);
1102 break;
1103 }
1104 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001105 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001106 break;
1107 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001108 }
1109 }
1110 }
1111
Vladimir Markoe079e212016-05-25 12:49:49 +01001112 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001113 ReportWriteFailure("method code", it);
1114 return false;
1115 }
1116 writer_->size_code_ += code_size;
1117 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001118 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001119 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001120 ++method_offsets_index_;
1121 }
1122
1123 return true;
1124 }
1125
1126 private:
1127 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001128 const size_t file_offset_;
1129 const ScopedObjectAccess soa_;
1130 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001131 ClassLinker* const class_linker_;
1132 mirror::DexCache* dex_cache_;
1133 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001134
1135 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1136 PLOG(ERROR) << "Failed to write " << what << " for "
1137 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1138 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001139
Mathieu Chartiere401d142015-04-22 13:56:20 -07001140 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001141 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001142 MethodReference ref = patch.TargetMethod();
1143 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001144 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1145 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001146 ArtMethod* method = dex_cache->GetResolvedMethod(
1147 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001148 CHECK(method != nullptr);
1149 return method;
1150 }
1151
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001152 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001153 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1154 // If there's no new compiled code, either we're compiling an app and the target method
1155 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001156 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001158 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001159 PointerSize size =
1160 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001161 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1162 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001163 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001164 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1165 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1166 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1167 target_offset = PointerToLowMemUInt32(oat_code_offset);
1168 } else {
1169 target_offset = target->IsNative()
1170 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1171 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1172 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001173 }
1174 return target_offset;
1175 }
1176
Vladimir Marko052164a2016-04-27 13:54:18 +01001177 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001178 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001179 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001180 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001181 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1182 }
1183
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001184 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001185 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001186 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1187 CHECK(type != nullptr);
1188 return type;
1189 }
1190
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001191 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001192 ScopedObjectAccessUnchecked soa(Thread::Current());
1193 StackHandleScope<1> hs(soa.Self());
1194 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1195 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1196 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1197 patch.TargetStringIndex(),
1198 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001199 DCHECK(string != nullptr);
1200 DCHECK(writer_->HasBootImage() ||
1201 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1202 return string;
1203 }
1204
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001205 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001206 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001207 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1208 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1209 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1210 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001211 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001212 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001213 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1214 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001215 }
1216 }
1217
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001218 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001219 DCHECK(writer_->HasBootImage());
1220 object = writer_->image_writer_->GetImageAddress(object);
1221 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1222 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1223 // TODO: Clean up offset types. The target offset must be treated as signed.
1224 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1225 }
1226
Vladimir Markof4da6752014-08-01 19:04:18 +01001227 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001228 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001229 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001230 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001231 } else {
1232 // NOTE: We're using linker patches for app->boot references when the image can
1233 // be relocated and therefore we need to emit .oat_patches. We're not using this
1234 // for app->app references, so check that the object is in the image space.
1235 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001236 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001237 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001238 uint32_t address = PointerToLowMemUInt32(object);
1239 DCHECK_LE(offset + 4, code->size());
1240 uint8_t* data = &(*code)[offset];
1241 data[0] = address & 0xffu;
1242 data[1] = (address >> 8) & 0xffu;
1243 data[2] = (address >> 16) & 0xffu;
1244 data[3] = (address >> 24) & 0xffu;
1245 }
1246
Mathieu Chartiere401d142015-04-22 13:56:20 -07001247 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001248 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001249 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001250 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001251 } else if (kIsDebugBuild) {
1252 // NOTE: We're using linker patches for app->boot references when the image can
1253 // be relocated and therefore we need to emit .oat_patches. We're not using this
1254 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001255 std::vector<gc::space::ImageSpace*> image_spaces =
1256 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1257 bool contains_method = false;
1258 for (gc::space::ImageSpace* image_space : image_spaces) {
1259 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1260 contains_method |=
1261 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1262 }
1263 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001264 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001265 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001266 uint32_t address = PointerToLowMemUInt32(method);
1267 DCHECK_LE(offset + 4, code->size());
1268 uint8_t* data = &(*code)[offset];
1269 data[0] = address & 0xffu;
1270 data[1] = (address >> 8) & 0xffu;
1271 data[2] = (address >> 16) & 0xffu;
1272 data[3] = (address >> 24) & 0xffu;
1273 }
1274
Vladimir Markof4da6752014-08-01 19:04:18 +01001275 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001276 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001277 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001278 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001279 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1280 // TODO: Clean up offset types.
1281 // The target_offset must be treated as signed for cross-oat patching.
1282 const void* target = reinterpret_cast<const void*>(
1283 writer_->image_writer_->GetOatDataBegin(oat_index) +
1284 static_cast<int32_t>(target_offset));
1285 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001286 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001287 DCHECK_LE(offset + 4, code->size());
1288 uint8_t* data = &(*code)[offset];
1289 data[0] = address & 0xffu;
1290 data[1] = (address >> 8) & 0xffu;
1291 data[2] = (address >> 16) & 0xffu;
1292 data[3] = (address >> 24) & 0xffu;
1293 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001294};
1295
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001296class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1297 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001298 WriteMapMethodVisitor(OatWriter* writer,
1299 OutputStream* out,
1300 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001301 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001302 : OatDexMethodVisitor(writer, relative_offset),
1303 out_(out),
1304 file_offset_(file_offset) {
1305 }
1306
1307 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001308 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001309 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1310
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001311 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001312 size_t file_offset = file_offset_;
1313 OutputStream* out = out_;
1314
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001315 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1316 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001317 ++method_offsets_index_;
1318
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001319 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1320 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1321 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1322 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1323
1324 if (map_offset != 0u) {
1325 // Transform map_offset to actual oat data offset.
1326 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1327 DCHECK_NE(map_offset, 0u);
1328 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1329
1330 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1331 size_t map_size = map.size() * sizeof(map[0]);
1332 if (map_offset == offset_) {
1333 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001334 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001335 ReportWriteFailure(it);
1336 return false;
1337 }
1338 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001339 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001340 }
1341 DCHECK_OFFSET_();
1342 }
1343
1344 return true;
1345 }
1346
1347 private:
1348 OutputStream* const out_;
1349 size_t const file_offset_;
1350
1351 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001352 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001353 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1354 }
1355};
1356
1357// Visit all methods from all classes in all dex files with the specified visitor.
1358bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1359 for (const DexFile* dex_file : *dex_files_) {
1360 const size_t class_def_count = dex_file->NumClassDefs();
1361 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1362 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1363 return false;
1364 }
1365 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001366 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001367 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001368 ClassDataItemIterator it(*dex_file, class_data);
1369 while (it.HasNextStaticField()) {
1370 it.Next();
1371 }
1372 while (it.HasNextInstanceField()) {
1373 it.Next();
1374 }
1375 size_t class_def_method_index = 0u;
1376 while (it.HasNextDirectMethod()) {
1377 if (!visitor->VisitMethod(class_def_method_index, it)) {
1378 return false;
1379 }
1380 ++class_def_method_index;
1381 it.Next();
1382 }
1383 while (it.HasNextVirtualMethod()) {
1384 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1385 return false;
1386 }
1387 ++class_def_method_index;
1388 it.Next();
1389 }
1390 }
1391 if (UNLIKELY(!visitor->EndClass())) {
1392 return false;
1393 }
1394 }
1395 }
1396 return true;
1397}
1398
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001399size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1400 const InstructionSetFeatures* instruction_set_features,
1401 uint32_t num_dex_files,
1402 SafeMap<std::string, std::string>* key_value_store) {
1403 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1404 oat_header_.reset(OatHeader::Create(instruction_set,
1405 instruction_set_features,
1406 num_dex_files,
1407 key_value_store));
1408 size_oat_header_ += sizeof(OatHeader);
1409 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001410 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001411}
1412
1413size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001414 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1415 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001416 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001417 oat_dex_file.offset_ = offset;
1418 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001419 }
1420 return offset;
1421}
1422
Brian Carlstrom389efb02012-01-11 12:06:26 -08001423size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001424 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001425 InitOatClassesMethodVisitor visitor(this, offset);
1426 bool success = VisitDexMethods(&visitor);
1427 CHECK(success);
1428 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001429
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001430 // Update oat_dex_files_.
1431 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001432 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1433 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001435 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001436 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001437 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001438 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001439 CHECK(oat_class_it == oat_classes_.end());
1440
1441 return offset;
1442}
1443
1444size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001445 InitMapMethodVisitor visitor(this, offset);
1446 bool success = VisitDexMethods(&visitor);
1447 DCHECK(success);
1448 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001449
Brian Carlstrome24fa612011-09-29 00:53:55 -07001450 return offset;
1451}
1452
1453size_t OatWriter::InitOatCode(size_t offset) {
1454 // calculate the offsets within OatHeader to executable code
1455 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001456 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001457 // required to be on a new page boundary
1458 offset = RoundUp(offset, kPageSize);
1459 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001460 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001461 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001462 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001463
Ian Rogers848871b2013-08-05 10:56:33 -07001464 #define DO_TRAMPOLINE(field, fn_name) \
1465 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001466 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1467 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001468 (field) = compiler_driver_->Create ## fn_name(); \
1469 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001470
Ian Rogers848871b2013-08-05 10:56:33 -07001471 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001472 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001473 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001474 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1475 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001476
Ian Rogers848871b2013-08-05 10:56:33 -07001477 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001478 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001479 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1480 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1481 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001482 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001483 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001484 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001485 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001486 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001487 return offset;
1488}
1489
1490size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001491 #define VISIT(VisitorType) \
1492 do { \
1493 VisitorType visitor(this, offset); \
1494 bool success = VisitDexMethods(&visitor); \
1495 DCHECK(success); \
1496 offset = visitor.GetOffset(); \
1497 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001498
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001499 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001500 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001501 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001502 }
Logan Chien8b977d32012-02-21 19:14:55 +08001503
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001504 #undef VISIT
1505
Brian Carlstrome24fa612011-09-29 00:53:55 -07001506 return offset;
1507}
1508
David Srbeckybc90fd02015-04-22 19:40:27 +01001509bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001510 CHECK(write_state_ == WriteState::kWriteRoData);
1511
Vladimir Markoe079e212016-05-25 12:49:49 +01001512 // Wrap out to update checksum with each write.
1513 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1514 out = &checksum_updating_out;
1515
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001516 if (!WriteClassOffsets(out)) {
1517 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001518 return false;
1519 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001520
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001521 if (!WriteClasses(out)) {
1522 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001523 return false;
1524 }
1525
Vladimir Markof4da6752014-08-01 19:04:18 +01001526 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001527 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001528 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1529 return false;
1530 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001531 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001532 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001533 relative_offset = WriteMaps(out, file_offset, relative_offset);
1534 if (relative_offset == 0) {
1535 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1536 return false;
1537 }
1538
David Srbeckybc90fd02015-04-22 19:40:27 +01001539 // Write padding.
1540 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1541 relative_offset += size_executable_offset_alignment_;
1542 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1543 size_t expected_file_offset = file_offset + relative_offset;
1544 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1545 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1546 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1547 return 0;
1548 }
1549 DCHECK_OFFSET();
1550
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001551 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001552 return true;
1553}
1554
1555bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001556 CHECK(write_state_ == WriteState::kWriteText);
1557
Vladimir Markoe079e212016-05-25 12:49:49 +01001558 // Wrap out to update checksum with each write.
1559 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1560 out = &checksum_updating_out;
1561
Vladimir Marko944da602016-02-19 12:27:55 +00001562 SetMultiOatRelativePatcherAdjustment();
1563
David Srbeckybc90fd02015-04-22 19:40:27 +01001564 const size_t file_offset = oat_data_offset_;
1565 size_t relative_offset = oat_header_->GetExecutableOffset();
1566 DCHECK_OFFSET();
1567
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001568 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001569 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001570 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001571 return false;
1572 }
1573
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001574 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1575 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001576 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001577 return false;
1578 }
1579
Vladimir Markof4da6752014-08-01 19:04:18 +01001580 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001581 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001582 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1583 return false;
1584 }
1585
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001586 if (kIsDebugBuild) {
1587 uint32_t size_total = 0;
1588 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001589 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1590 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001591
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001592 DO_STAT(size_dex_file_alignment_);
1593 DO_STAT(size_executable_offset_alignment_);
1594 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001595 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001596 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001597 DO_STAT(size_interpreter_to_interpreter_bridge_);
1598 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1599 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001600 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001601 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001602 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001603 DO_STAT(size_quick_to_interpreter_bridge_);
1604 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001605 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001606 DO_STAT(size_code_);
1607 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001608 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001609 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001610 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001611 DO_STAT(size_oat_dex_file_location_size_);
1612 DO_STAT(size_oat_dex_file_location_data_);
1613 DO_STAT(size_oat_dex_file_location_checksum_);
1614 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001615 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001616 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001617 DO_STAT(size_oat_lookup_table_alignment_);
1618 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001619 DO_STAT(size_oat_class_offsets_alignment_);
1620 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001621 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001622 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001623 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001624 DO_STAT(size_oat_class_method_offsets_);
1625 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001626
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001627 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001628 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001629 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001630 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001631
Vladimir Markof4da6752014-08-01 19:04:18 +01001632 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001633 CHECK_EQ(size_, relative_offset);
1634
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001635 write_state_ = WriteState::kWriteHeader;
1636 return true;
1637}
1638
1639bool OatWriter::WriteHeader(OutputStream* out,
1640 uint32_t image_file_location_oat_checksum,
1641 uintptr_t image_file_location_oat_begin,
1642 int32_t image_patch_delta) {
1643 CHECK(write_state_ == WriteState::kWriteHeader);
1644
1645 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1646 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1647 if (compiler_driver_->IsBootImage()) {
1648 CHECK_EQ(image_patch_delta, 0);
1649 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1650 } else {
1651 CHECK_ALIGNED(image_patch_delta, kPageSize);
1652 oat_header_->SetImagePatchDelta(image_patch_delta);
1653 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001654 oat_header_->UpdateChecksumWithHeaderData();
1655
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001656 const size_t file_offset = oat_data_offset_;
1657
1658 off_t current_offset = out->Seek(0, kSeekCurrent);
1659 if (current_offset == static_cast<off_t>(-1)) {
1660 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1661 return false;
1662 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001663 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001664 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1665 return false;
1666 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001667 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001668
1669 // Flush all other data before writing the header.
1670 if (!out->Flush()) {
1671 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1672 return false;
1673 }
1674 // Write the header.
1675 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001676 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001677 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1678 return false;
1679 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001680 // Flush the header data.
1681 if (!out->Flush()) {
1682 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001683 return false;
1684 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001685
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001686 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1687 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1688 return false;
1689 }
1690 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1691
1692 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001693 return true;
1694}
1695
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001696bool OatWriter::WriteClassOffsets(OutputStream* out) {
1697 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1698 if (oat_dex_file.class_offsets_offset_ != 0u) {
1699 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1700 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1701 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1702 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1703 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001704 return false;
1705 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001706 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1707 return false;
1708 }
1709 }
1710 }
1711 return true;
1712}
1713
1714bool OatWriter::WriteClasses(OutputStream* out) {
1715 for (OatClass& oat_class : oat_classes_) {
1716 if (!oat_class.Write(this, out, oat_data_offset_)) {
1717 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1718 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001719 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001720 }
1721 return true;
1722}
1723
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001724size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001725 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001726 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1727 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1728 return 0;
1729 }
1730 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001731 size_vmap_table_ = relative_offset - vmap_tables_offset;
1732
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001733 return relative_offset;
1734}
1735
1736size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001737 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001738 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001739
Ian Rogers848871b2013-08-05 10:56:33 -07001740 #define DO_TRAMPOLINE(field) \
1741 do { \
1742 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1743 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001744 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001745 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001746 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001747 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001748 return false; \
1749 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001750 size_ ## field += (field)->size(); \
1751 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001752 DCHECK_OFFSET(); \
1753 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001754
Ian Rogers848871b2013-08-05 10:56:33 -07001755 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001756 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001757 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001758 DO_TRAMPOLINE(quick_resolution_trampoline_);
1759 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1760 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001761 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001762 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001763}
1764
Ian Rogers3d504072014-03-01 09:16:49 -08001765size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001766 const size_t file_offset,
1767 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001768 #define VISIT(VisitorType) \
1769 do { \
1770 VisitorType visitor(this, out, file_offset, relative_offset); \
1771 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1772 return 0; \
1773 } \
1774 relative_offset = visitor.GetOffset(); \
1775 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001776
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001777 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001778
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001779 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001780
Vladimir Markob163bb72015-03-31 21:49:49 +01001781 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1782 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1783 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1784
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001785 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001786}
1787
Vladimir Marko944da602016-02-19 12:27:55 +00001788bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001789 // Get the elf file offset of the oat file.
1790 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1791 if (raw_file_offset == static_cast<off_t>(-1)) {
1792 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1793 return false;
1794 }
1795 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1796 return true;
1797}
1798
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001799bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1800 // Read the dex file header and perform minimal verification.
1801 uint8_t raw_header[sizeof(DexFile::Header)];
1802 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1803 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1804 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1805 return false;
1806 }
1807 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1808 return false;
1809 }
1810
1811 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1812 oat_dex_file->dex_file_size_ = header->file_size_;
1813 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1814 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1815 return true;
1816}
1817
1818bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1819 if (!DexFile::IsMagicValid(raw_header)) {
1820 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1821 return false;
1822 }
1823 if (!DexFile::IsVersionValid(raw_header)) {
1824 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1825 return false;
1826 }
1827 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1828 if (header->file_size_ < sizeof(DexFile::Header)) {
1829 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1830 << " File: " << location;
1831 return false;
1832 }
1833 return true;
1834}
1835
1836bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1837 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1838
1839 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001840 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001841 return false;
1842 }
1843
1844 // Write dex files.
1845 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1846 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1847 return false;
1848 }
1849 }
1850
1851 // Close sources.
1852 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1853 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1854 }
1855 zipped_dex_files_.clear();
1856 zip_archives_.clear();
1857 raw_dex_files_.clear();
1858 return true;
1859}
1860
1861bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1862 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1863 return false;
1864 }
1865 if (oat_dex_file->source_.IsZipEntry()) {
1866 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1867 return false;
1868 }
1869 } else if (oat_dex_file->source_.IsRawFile()) {
1870 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1871 return false;
1872 }
1873 } else {
1874 DCHECK(oat_dex_file->source_.IsRawData());
1875 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1876 return false;
1877 }
1878 }
1879
1880 // Update current size and account for the written data.
1881 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1882 size_ += oat_dex_file->dex_file_size_;
1883 size_dex_file_ += oat_dex_file->dex_file_size_;
1884 return true;
1885}
1886
1887bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1888 // Dex files are required to be 4 byte aligned.
1889 size_t original_offset = size_;
1890 size_t offset = RoundUp(original_offset, 4);
1891 size_dex_file_alignment_ += offset - original_offset;
1892
1893 // Seek to the start of the dex file and flush any pending operations in the stream.
1894 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1895 uint32_t start_offset = oat_data_offset_ + offset;
1896 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1897 if (actual_offset != static_cast<off_t>(start_offset)) {
1898 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1899 << " Expected: " << start_offset
1900 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1901 return false;
1902 }
1903 if (!out->Flush()) {
1904 PLOG(ERROR) << "Failed to flush before writing dex file."
1905 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1906 return false;
1907 }
1908 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1909 if (actual_offset != static_cast<off_t>(start_offset)) {
1910 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1911 << " Expected: " << start_offset
1912 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1913 return false;
1914 }
1915
1916 size_ = offset;
1917 oat_dex_file->dex_file_offset_ = offset;
1918 return true;
1919}
1920
1921bool OatWriter::WriteDexFile(OutputStream* rodata,
1922 File* file,
1923 OatDexFile* oat_dex_file,
1924 ZipEntry* dex_file) {
1925 size_t start_offset = oat_data_offset_ + size_;
1926 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1927
1928 // Extract the dex file and get the extracted size.
1929 std::string error_msg;
1930 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1931 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1932 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1933 return false;
1934 }
1935 if (file->Flush() != 0) {
1936 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1937 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1938 return false;
1939 }
1940 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1941 if (extracted_end == static_cast<off_t>(-1)) {
1942 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1943 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1944 return false;
1945 }
1946 if (extracted_end < static_cast<off_t>(start_offset)) {
1947 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1948 << " Start: " << start_offset
1949 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1950 return false;
1951 }
1952 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1953 if (extracted_size < sizeof(DexFile::Header)) {
1954 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1955 << extracted_size << " File: " << oat_dex_file->GetLocation();
1956 return false;
1957 }
1958
1959 // Read the dex file header and extract required data to OatDexFile.
1960 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1961 if (actual_offset != static_cast<off_t>(start_offset)) {
1962 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1963 << " Expected: " << start_offset
1964 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1965 return false;
1966 }
1967 if (!ReadDexFileHeader(file, oat_dex_file)) {
1968 return false;
1969 }
1970 if (extracted_size < oat_dex_file->dex_file_size_) {
1971 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1972 << " file size from header: " << oat_dex_file->dex_file_size_
1973 << " File: " << oat_dex_file->GetLocation();
1974 return false;
1975 }
1976
1977 // Override the checksum from header with the CRC from ZIP entry.
1978 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1979
1980 // Seek both file and stream to the end offset.
1981 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1982 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1983 if (actual_offset != static_cast<off_t>(end_offset)) {
1984 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1985 << " Expected: " << end_offset
1986 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1987 return false;
1988 }
1989 actual_offset = rodata->Seek(end_offset, kSeekSet);
1990 if (actual_offset != static_cast<off_t>(end_offset)) {
1991 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1992 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1993 return false;
1994 }
1995 if (!rodata->Flush()) {
1996 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1997 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1998 return false;
1999 }
2000
2001 // If we extracted more than the size specified in the header, truncate the file.
2002 if (extracted_size > oat_dex_file->dex_file_size_) {
2003 if (file->SetLength(end_offset) != 0) {
2004 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2005 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2006 return false;
2007 }
2008 }
2009
2010 return true;
2011}
2012
2013bool OatWriter::WriteDexFile(OutputStream* rodata,
2014 File* file,
2015 OatDexFile* oat_dex_file,
2016 File* dex_file) {
2017 size_t start_offset = oat_data_offset_ + size_;
2018 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2019
2020 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2021 if (input_offset != static_cast<off_t>(0)) {
2022 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2023 << " Expected: 0"
2024 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2025 return false;
2026 }
2027 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2028 return false;
2029 }
2030
2031 // Copy the input dex file using sendfile().
2032 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2033 PLOG(ERROR) << "Failed to copy dex file to oat file."
2034 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2035 return false;
2036 }
2037 if (file->Flush() != 0) {
2038 PLOG(ERROR) << "Failed to flush dex file."
2039 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2040 return false;
2041 }
2042
2043 // Check file position and seek the stream to the end offset.
2044 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2045 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2046 if (actual_offset != static_cast<off_t>(end_offset)) {
2047 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2048 << " Expected: " << end_offset
2049 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2050 return false;
2051 }
2052 actual_offset = rodata->Seek(end_offset, kSeekSet);
2053 if (actual_offset != static_cast<off_t>(end_offset)) {
2054 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2055 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2056 return false;
2057 }
2058 if (!rodata->Flush()) {
2059 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2060 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2061 return false;
2062 }
2063
2064 return true;
2065}
2066
2067bool OatWriter::WriteDexFile(OutputStream* rodata,
2068 OatDexFile* oat_dex_file,
2069 const uint8_t* dex_file) {
2070 // Note: The raw data has already been checked to contain the header
2071 // and all the data that the header specifies as the file size.
2072 DCHECK(dex_file != nullptr);
2073 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2074 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2075
Vladimir Markoe079e212016-05-25 12:49:49 +01002076 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002077 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2078 << " to " << rodata->GetLocation();
2079 return false;
2080 }
2081 if (!rodata->Flush()) {
2082 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2083 << " File: " << oat_dex_file->GetLocation();
2084 return false;
2085 }
2086
2087 // Update dex file size and resize class offsets in the OatDexFile.
2088 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2089 oat_dex_file->dex_file_size_ = header->file_size_;
2090 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2091 return true;
2092}
2093
2094bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2095 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2096
2097 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2098 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2099 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2100 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2101 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2102 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2103 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2104 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2105 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2106 return false;
2107 }
2108
2109 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2110 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2111
2112 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2113 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2114
2115 // Write OatDexFile.
2116 if (!oat_dex_file->Write(this, rodata)) {
2117 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2118 return false;
2119 }
2120 }
2121
2122 return true;
2123}
2124
David Brazdilb92ba622016-09-01 16:00:30 +00002125bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2126 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2127
2128 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2129 if (file->SetLength(new_length) != 0) {
2130 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2131 << "File: " << file->GetPath();
2132 return false;
2133 }
2134 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2135 if (actual_offset != static_cast<off_t>(new_length)) {
2136 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2137 << " Actual: " << actual_offset << " Expected: " << new_length
2138 << " File: " << rodata->GetLocation();
2139 return false;
2140 }
2141 if (!rodata->Flush()) {
2142 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2143 << " File: " << rodata->GetLocation();
2144 return false;
2145 }
2146 return true;
2147}
2148
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002149bool OatWriter::OpenDexFiles(
2150 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002151 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002152 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2153 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2154 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2155
2156 if (oat_dex_files_.empty()) {
2157 // Nothing to do.
2158 return true;
2159 }
2160
2161 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2162 size_t length = size_ - map_offset;
2163 std::string error_msg;
2164 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2165 PROT_READ | PROT_WRITE,
2166 MAP_SHARED,
2167 file->Fd(),
2168 oat_data_offset_ + map_offset,
2169 /* low_4gb */ false,
2170 file->GetPath().c_str(),
2171 &error_msg));
2172 if (dex_files_map == nullptr) {
2173 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2174 << " error: " << error_msg;
2175 return false;
2176 }
2177 std::vector<std::unique_ptr<const DexFile>> dex_files;
2178 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2179 // Make sure no one messed with input files while we were copying data.
2180 // At the very least we need consistent file size and number of class definitions.
2181 const uint8_t* raw_dex_file =
2182 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2183 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2184 // Note: ValidateDexFileHeader() already logged an error message.
2185 LOG(ERROR) << "Failed to verify written dex file header!"
2186 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2187 << " ~ " << static_cast<const void*>(raw_dex_file);
2188 return false;
2189 }
2190 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2191 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2192 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2193 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2194 << " Output: " << file->GetPath();
2195 return false;
2196 }
2197 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2198 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2199 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2200 << " Output: " << file->GetPath();
2201 return false;
2202 }
2203
2204 // Now, open the dex file.
2205 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2206 oat_dex_file.dex_file_size_,
2207 oat_dex_file.GetLocation(),
2208 oat_dex_file.dex_file_location_checksum_,
2209 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002210 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002211 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002212 &error_msg));
2213 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002214 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2215 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002216 return false;
2217 }
2218 }
2219
2220 *opened_dex_files_map = std::move(dex_files_map);
2221 *opened_dex_files = std::move(dex_files);
2222 return true;
2223}
2224
2225bool OatWriter::WriteTypeLookupTables(
David Brazdilb92ba622016-09-01 16:00:30 +00002226 MemMap* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002227 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2228 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2229
2230 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2231 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2232 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdilb92ba622016-09-01 16:00:30 +00002233 if (oat_dex_file->lookup_table_offset_ != 0u) {
2234 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2235 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2236 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2237 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2238 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2239 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002240 }
2241 }
2242
David Brazdilb92ba622016-09-01 16:00:30 +00002243 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2244 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2245 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002246 return false;
2247 }
2248
2249 return true;
2250}
2251
Vladimir Markof4da6752014-08-01 19:04:18 +01002252bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2253 static const uint8_t kPadding[] = {
2254 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2255 };
2256 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002257 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002258 return false;
2259 }
2260 size_code_alignment_ += aligned_code_delta;
2261 return true;
2262}
2263
Vladimir Marko944da602016-02-19 12:27:55 +00002264void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2265 DCHECK(dex_files_ != nullptr);
2266 DCHECK(relative_patcher_ != nullptr);
2267 DCHECK_NE(oat_data_offset_, 0u);
2268 if (image_writer_ != nullptr && !dex_files_->empty()) {
2269 // The oat data begin may not be initialized yet but the oat file offset is ready.
2270 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2271 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2272 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002273 }
2274}
2275
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002276OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2277 DexFileSource source,
2278 CreateTypeLookupTable create_type_lookup_table)
2279 : source_(source),
2280 create_type_lookup_table_(create_type_lookup_table),
2281 dex_file_size_(0),
2282 offset_(0),
2283 dex_file_location_size_(strlen(dex_file_location)),
2284 dex_file_location_data_(dex_file_location),
2285 dex_file_location_checksum_(0u),
2286 dex_file_offset_(0u),
2287 class_offsets_offset_(0u),
2288 lookup_table_offset_(0u),
2289 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002290}
2291
2292size_t OatWriter::OatDexFile::SizeOf() const {
2293 return sizeof(dex_file_location_size_)
2294 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002295 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002296 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002297 + sizeof(class_offsets_offset_)
2298 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002299}
2300
David Brazdilb92ba622016-09-01 16:00:30 +00002301void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2302 DCHECK_EQ(lookup_table_offset_, 0u);
2303 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2304 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2305 if (table_size != 0u) {
2306 // Type tables are required to be 4 byte aligned.
2307 size_t original_offset = oat_writer->size_;
2308 size_t offset = RoundUp(original_offset, 4);
2309 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2310 lookup_table_offset_ = offset;
2311 oat_writer->size_ = offset + table_size;
2312 oat_writer->size_oat_lookup_table_ += table_size;
2313 }
2314 }
2315}
2316
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002317void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2318 DCHECK_EQ(class_offsets_offset_, 0u);
2319 if (!class_offsets_.empty()) {
2320 // Class offsets are required to be 4 byte aligned.
2321 size_t original_offset = oat_writer->size_;
2322 size_t offset = RoundUp(original_offset, 4);
2323 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2324 class_offsets_offset_ = offset;
2325 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2326 }
2327}
2328
2329bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2330 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002331 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002332
Vladimir Markoe079e212016-05-25 12:49:49 +01002333 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002334 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002335 return false;
2336 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002337 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002338
Vladimir Markoe079e212016-05-25 12:49:49 +01002339 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002340 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002341 return false;
2342 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002343 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002344
Vladimir Markoe079e212016-05-25 12:49:49 +01002345 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002346 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002347 return false;
2348 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002349 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002350
Vladimir Markoe079e212016-05-25 12:49:49 +01002351 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002352 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002353 return false;
2354 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002355 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002356
Vladimir Markoe079e212016-05-25 12:49:49 +01002357 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002358 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2359 return false;
2360 }
2361 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2362
Vladimir Markoe079e212016-05-25 12:49:49 +01002363 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002364 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2365 return false;
2366 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002367 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002368
2369 return true;
2370}
2371
2372bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002373 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002374 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2375 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002376 return false;
2377 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002378 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002379 return true;
2380}
2381
Brian Carlstromba150c32013-08-27 17:31:03 -07002382OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002383 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002384 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002385 mirror::Class::Status status)
2386 : compiled_methods_(compiled_methods) {
2387 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002388 CHECK_LE(num_non_null_compiled_methods, num_methods);
2389
Brian Carlstrom265091e2013-01-30 14:08:26 -08002390 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002391 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2392
2393 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2394 // apply when there are 0 methods, we just arbitrarily say that 0
2395 // methods means kOatClassNoneCompiled and that we won't use
2396 // kOatClassAllCompiled unless there is at least one compiled
2397 // method. This means in an interpretter only system, we can assert
2398 // that all classes are kOatClassNoneCompiled.
2399 if (num_non_null_compiled_methods == 0) {
2400 type_ = kOatClassNoneCompiled;
2401 } else if (num_non_null_compiled_methods == num_methods) {
2402 type_ = kOatClassAllCompiled;
2403 } else {
2404 type_ = kOatClassSomeCompiled;
2405 }
2406
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002407 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002408 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002409 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002410
2411 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2412 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002413 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002414 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2415 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2416 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2417 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002418 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002419 method_bitmap_size_ = 0;
2420 }
2421
2422 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002423 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002424 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002425 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2426 } else {
2427 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2428 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2429 if (type_ == kOatClassSomeCompiled) {
2430 method_bitmap_->SetBit(i);
2431 }
2432 }
2433 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002434}
2435
Brian Carlstrom265091e2013-01-30 14:08:26 -08002436size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2437 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002438 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2439 if (method_offset == 0) {
2440 return 0;
2441 }
2442 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002443}
2444
2445size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2446 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002447 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002448}
2449
2450size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002451 return sizeof(status_)
2452 + sizeof(type_)
2453 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2454 + method_bitmap_size_
2455 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002456}
2457
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002458bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002459 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002460 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002461 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002462 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002463 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002464 return false;
2465 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002466 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002467
Vladimir Markoe079e212016-05-25 12:49:49 +01002468 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002469 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002470 return false;
2471 }
2472 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002473
Brian Carlstromba150c32013-08-27 17:31:03 -07002474 if (method_bitmap_size_ != 0) {
2475 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002476 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002477 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002478 return false;
2479 }
2480 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002481
Vladimir Markoe079e212016-05-25 12:49:49 +01002482 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002483 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002484 return false;
2485 }
2486 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2487 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002488
Vladimir Markoe079e212016-05-25 12:49:49 +01002489 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002490 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002491 return false;
2492 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002493 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002494 return true;
2495}
2496
Brian Carlstrome24fa612011-09-29 00:53:55 -07002497} // namespace art