blob: c9c5d24674973c07eee038da7380e802516459ae [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
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000229 void ReserveClassOffsets(OatWriter* oat_writer);
230
Vladimir Marko49b0f452015-12-10 13:49:19 +0000231 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000232 bool Write(OatWriter* oat_writer, OutputStream* out) const;
233 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
234
235 // The source of the dex file.
236 DexFileSource source_;
237
238 // Whether to create the type lookup table.
239 CreateTypeLookupTable create_type_lookup_table_;
240
241 // Dex file size. Initialized when writing the dex file.
242 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000243
244 // Offset of start of OatDexFile from beginning of OatHeader. It is
245 // used to validate file position when writing.
246 size_t offset_;
247
248 // Data to write.
249 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000250 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000251 uint32_t dex_file_location_checksum_;
252 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000253 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000254 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255
256 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000257 dchecked_vector<uint32_t> class_offsets_;
258
259 private:
260 size_t GetClassOffsetsRawSize() const {
261 return class_offsets_.size() * sizeof(class_offsets_[0]);
262 }
263
264 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
265};
266
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100267#define DCHECK_OFFSET() \
268 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
269 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
270
271#define DCHECK_OFFSET_() \
272 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
273 << "file_offset=" << file_offset << " offset_=" << offset_
274
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000275OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
276 : write_state_(WriteState::kAddingDexFileSources),
277 timings_(timings),
278 raw_dex_files_(),
279 zip_archives_(),
280 zipped_dex_files_(),
281 zipped_dex_file_locations_(),
282 compiler_driver_(nullptr),
283 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800284 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000285 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100286 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000287 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100288 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700289 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700290 size_dex_file_alignment_(0),
291 size_executable_offset_alignment_(0),
292 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700293 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700294 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700295 size_interpreter_to_interpreter_bridge_(0),
296 size_interpreter_to_compiled_code_bridge_(0),
297 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800298 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700299 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700300 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700301 size_quick_to_interpreter_bridge_(0),
302 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100303 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700304 size_code_(0),
305 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100306 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100307 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700308 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_oat_dex_file_location_size_(0),
310 size_oat_dex_file_location_data_(0),
311 size_oat_dex_file_location_checksum_(0),
312 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000313 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000314 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000315 size_oat_lookup_table_alignment_(0),
316 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000317 size_oat_class_offsets_alignment_(0),
318 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700319 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700320 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700321 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100322 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000323 relative_patcher_(nullptr),
324 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000325}
326
327bool OatWriter::AddDexFileSource(const char* filename,
328 const char* location,
329 CreateTypeLookupTable create_type_lookup_table) {
330 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
331 uint32_t magic;
332 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700333 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
334 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000335 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
336 return false;
337 } else if (IsDexMagic(magic)) {
338 // The file is open for reading, not writing, so it's OK to let the File destructor
339 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700340 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000341 oat_dex_files_.emplace_back(location,
342 DexFileSource(raw_dex_files_.back().get()),
343 create_type_lookup_table);
344 } else if (IsZipMagic(magic)) {
345 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
346 return false;
347 }
348 } else {
349 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
350 return false;
351 }
352 return true;
353}
354
355// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700356bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000357 const char* location,
358 CreateTypeLookupTable create_type_lookup_table) {
359 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
360 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700361 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000362 ZipArchive* zip_archive = zip_archives_.back().get();
363 if (zip_archive == nullptr) {
364 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
365 << error_msg;
366 return false;
367 }
368 for (size_t i = 0; ; ++i) {
369 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
370 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
371 if (entry == nullptr) {
372 break;
373 }
374 zipped_dex_files_.push_back(std::move(entry));
375 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
376 const char* full_location = zipped_dex_file_locations_.back().c_str();
377 oat_dex_files_.emplace_back(full_location,
378 DexFileSource(zipped_dex_files_.back().get()),
379 create_type_lookup_table);
380 }
381 if (zipped_dex_file_locations_.empty()) {
382 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
383 return false;
384 }
385 return true;
386}
387
388// Add dex file source from raw memory.
389bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
390 const char* location,
391 uint32_t location_checksum,
392 CreateTypeLookupTable create_type_lookup_table) {
393 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
394 if (data.size() < sizeof(DexFile::Header)) {
395 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
396 << data.size() << " File: " << location;
397 return false;
398 }
399 if (!ValidateDexFileHeader(data.data(), location)) {
400 return false;
401 }
402 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
403 if (data.size() < header->file_size_) {
404 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
405 << " file size from header: " << header->file_size_ << " File: " << location;
406 return false;
407 }
408
409 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
410 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
411 return true;
412}
413
414dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
415 dchecked_vector<const char*> locations;
416 locations.reserve(oat_dex_files_.size());
417 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
418 locations.push_back(oat_dex_file.GetLocation());
419 }
420 return locations;
421}
422
423bool OatWriter::WriteAndOpenDexFiles(
424 OutputStream* rodata,
425 File* file,
426 InstructionSet instruction_set,
427 const InstructionSetFeatures* instruction_set_features,
428 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800429 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000430 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
431 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
432 CHECK(write_state_ == WriteState::kAddingDexFileSources);
433
434 size_t offset = InitOatHeader(instruction_set,
435 instruction_set_features,
436 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
437 key_value_store);
David Brazdil181e1cc2016-09-01 16:38:47 +0000438 size_ = InitOatDexFiles(offset);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000439
440 std::unique_ptr<MemMap> dex_files_map;
441 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil181e1cc2016-09-01 16:38:47 +0000442 if (!WriteDexFiles(rodata, file) ||
443 !OpenDexFiles(file, verify, &dex_files_map, &dex_files)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 return false;
445 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000446
447 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
448 // difficult because we're not using the OutputStream directly.
449 if (!oat_dex_files_.empty()) {
450 size_t size = size_ - oat_dex_files_[0].dex_file_offset_;
451 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000453
454 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
455
456 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
457 return false;
458 }
459
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000460 // Reserve space for class offsets and update class_offsets_offset_.
461 for (OatDexFile& oat_dex_file : oat_dex_files_) {
462 oat_dex_file.ReserveClassOffsets(this);
463 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100464
David Brazdil181e1cc2016-09-01 16:38:47 +0000465 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
466 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000467 }
468
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000469 *opened_dex_files_map = std::move(dex_files_map);
470 *opened_dex_files = std::move(dex_files);
471 write_state_ = WriteState::kPrepareLayout;
472 return true;
473}
474
475void OatWriter::PrepareLayout(const CompilerDriver* compiler,
476 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000477 const std::vector<const DexFile*>& dex_files,
478 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000479 CHECK(write_state_ == WriteState::kPrepareLayout);
480
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 compiler_driver_ = compiler;
482 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000483 dex_files_ = &dex_files;
484 relative_patcher_ = relative_patcher;
485 SetMultiOatRelativePatcherAdjustment();
486
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000487 if (compiling_boot_image_) {
488 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800489 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100490 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000491 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100492
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800494 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800496 offset = InitOatClasses(offset);
497 }
498 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000499 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100500 offset = InitOatMaps(offset);
501 }
502 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000503 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800504 offset = InitOatCode(offset);
505 }
506 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000507 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800508 offset = InitOatCodeDexFiles(offset);
509 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700510 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700511
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800512 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100513 // Allocate space for app dex cache arrays in the .bss section.
514 size_t bss_start = RoundUp(size_, kPageSize);
Andreas Gampe542451c2016-07-26 09:02:02 -0700515 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100516 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000517 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100518 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
519 DexCacheArraysLayout layout(pointer_size, dex_file);
520 bss_size_ += layout.Size();
521 }
522 }
523
Brian Carlstrome24fa612011-09-29 00:53:55 -0700524 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800525 if (compiling_boot_image_) {
526 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000527 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800528 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000529
530 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700531}
532
Ian Rogers0571d352011-11-03 19:51:38 -0700533OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700534}
535
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100536class OatWriter::DexMethodVisitor {
537 public:
538 DexMethodVisitor(OatWriter* writer, size_t offset)
539 : writer_(writer),
540 offset_(offset),
541 dex_file_(nullptr),
542 class_def_index_(DexFile::kDexNoIndex) {
543 }
544
545 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
546 DCHECK(dex_file_ == nullptr);
547 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
548 dex_file_ = dex_file;
549 class_def_index_ = class_def_index;
550 return true;
551 }
552
553 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
554
555 virtual bool EndClass() {
556 if (kIsDebugBuild) {
557 dex_file_ = nullptr;
558 class_def_index_ = DexFile::kDexNoIndex;
559 }
560 return true;
561 }
562
563 size_t GetOffset() const {
564 return offset_;
565 }
566
567 protected:
568 virtual ~DexMethodVisitor() { }
569
570 OatWriter* const writer_;
571
572 // The offset is usually advanced for each visited method by the derived class.
573 size_t offset_;
574
575 // The dex file and class def index are set in StartClass().
576 const DexFile* dex_file_;
577 size_t class_def_index_;
578};
579
580class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
581 public:
582 OatDexMethodVisitor(OatWriter* writer, size_t offset)
583 : DexMethodVisitor(writer, offset),
584 oat_class_index_(0u),
585 method_offsets_index_(0u) {
586 }
587
588 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
589 DexMethodVisitor::StartClass(dex_file, class_def_index);
590 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
591 method_offsets_index_ = 0u;
592 return true;
593 }
594
595 bool EndClass() {
596 ++oat_class_index_;
597 return DexMethodVisitor::EndClass();
598 }
599
600 protected:
601 size_t oat_class_index_;
602 size_t method_offsets_index_;
603};
604
605class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
606 public:
607 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
608 : DexMethodVisitor(writer, offset),
609 compiled_methods_(),
610 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000611 size_t num_classes = 0u;
612 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
613 num_classes += oat_dex_file.class_offsets_.size();
614 }
615 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100616 compiled_methods_.reserve(256u);
617 }
618
619 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
620 DexMethodVisitor::StartClass(dex_file, class_def_index);
621 compiled_methods_.clear();
622 num_non_null_compiled_methods_ = 0u;
623 return true;
624 }
625
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300626 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
627 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100628 // Fill in the compiled_methods_ array for methods that have a
629 // CompiledMethod. We track the number of non-null entries in
630 // num_non_null_compiled_methods_ since we only want to allocate
631 // OatMethodOffsets for the compiled methods.
632 uint32_t method_idx = it.GetMemberIndex();
633 CompiledMethod* compiled_method =
634 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
635 compiled_methods_.push_back(compiled_method);
636 if (compiled_method != nullptr) {
637 ++num_non_null_compiled_methods_;
638 }
639 return true;
640 }
641
642 bool EndClass() {
643 ClassReference class_ref(dex_file_, class_def_index_);
644 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
645 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700646 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100647 status = compiled_class->GetStatus();
648 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
649 status = mirror::Class::kStatusError;
650 } else {
651 status = mirror::Class::kStatusNotReady;
652 }
653
Vladimir Marko49b0f452015-12-10 13:49:19 +0000654 writer_->oat_classes_.emplace_back(offset_,
655 compiled_methods_,
656 num_non_null_compiled_methods_,
657 status);
658 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100659 return DexMethodVisitor::EndClass();
660 }
661
662 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000663 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100664 size_t num_non_null_compiled_methods_;
665};
666
667class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
668 public:
669 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100670 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100671 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100672 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100673 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
674 }
675
676 bool EndClass() {
677 OatDexMethodVisitor::EndClass();
678 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100679 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100680 }
681 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100682 }
683
684 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700685 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000686 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
688
689 if (compiled_method != nullptr) {
690 // Derived from CompiledMethod.
691 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100692
Vladimir Marko35831e82015-09-11 11:59:18 +0100693 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
694 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800695 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800696
David Srbecky009e2a62015-04-15 02:46:30 +0100697 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100698 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800699 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000700 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000701 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
702 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800703 // Duplicate methods, we want the same code for both of them so that the oat writer puts
704 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800705 } else {
706 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100707 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800708 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000709 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100710 quick_code_offset = dedupe_map_.GetOrCreate(
711 compiled_method,
712 [this, &deduped, compiled_method, &it, thumb_offset]() {
713 deduped = false;
714 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
715 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800716 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100717
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100718 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000719 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100720 // TODO: Should this be a hard failure?
721 LOG(WARNING) << "Multiple definitions of "
722 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000723 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
724 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100725 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000726 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100727 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800728 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100729
Elliott Hughes956af0f2014-12-11 14:34:28 -0800730 // Update quick method header.
731 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
732 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800733 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100734 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
735 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100736 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800737 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
738 // to 0-offset and we need to adjust it by code_offset.
739 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100740 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800741 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100742 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800743 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800744 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
745 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
746 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100747 *method_header = OatQuickMethodHeader(vmap_table_offset,
748 frame_size_in_bytes,
749 core_spill_mask,
750 fp_spill_mask,
751 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100752
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000753 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800754 // Update offsets. (Checksum is updated when writing.)
755 offset_ += sizeof(*method_header); // Method header is prepended before code.
756 offset_ += code_size;
757 // Record absolute patch locations.
758 if (!compiled_method->GetPatches().empty()) {
759 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
760 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000761 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100762 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100763 }
764 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100765 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800766 }
Alex Light78382fa2014-06-06 15:45:32 -0700767
David Srbecky91cc06c2016-03-07 16:13:58 +0000768 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000769 // Exclude quickened dex methods (code_size == 0) since they have no native code.
770 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
771 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800772 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000773 debug::MethodDebugInfo info = debug::MethodDebugInfo();
774 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000775 info.dex_file = dex_file_;
776 info.class_def_index = class_def_index_;
777 info.dex_method_index = it.GetMemberIndex();
778 info.access_flags = it.GetMethodAccessFlags();
779 info.code_item = it.GetMethodCodeItem();
780 info.isa = compiled_method->GetInstructionSet();
781 info.deduped = deduped;
782 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
783 info.is_optimized = method_header->IsOptimized();
784 info.is_code_address_text_relative = true;
785 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
786 info.code_size = code_size;
787 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
788 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
789 info.cfi = compiled_method->GetCFIInfo();
790 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100791 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100792
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100793 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
794 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
795 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100796 ++method_offsets_index_;
797 }
798
799 return true;
800 }
801
802 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000803 struct CodeOffsetsKeyComparator {
804 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100805 // Code is deduplicated by CompilerDriver, compare only data pointers.
806 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
807 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000808 }
809 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100810 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
811 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000812 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100813 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
814 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000815 }
816 return false;
817 }
818 };
819
David Srbecky009e2a62015-04-15 02:46:30 +0100820 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
821 const ClassDataItemIterator& it,
822 uint32_t thumb_offset) {
823 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100824 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100825 offset_ += CodeAlignmentSize(offset_, *compiled_method);
826 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100827 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
828 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
829 }
830
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100831 // Deduplication is already done on a pointer basis by the compiler driver,
832 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100833 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100834
David Srbecky009e2a62015-04-15 02:46:30 +0100835 // Cache of compiler's --debuggable option.
836 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100837};
838
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100839class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
840 public:
841 InitMapMethodVisitor(OatWriter* writer, size_t offset)
842 : OatDexMethodVisitor(writer, offset) {
843 }
844
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700845 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700846 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000847 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100848 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
849
850 if (compiled_method != nullptr) {
851 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100852 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100853
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100854 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100855 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100856 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100857 size_t offset = dedupe_map_.GetOrCreate(
858 map.data(),
859 [this, map_size]() {
860 uint32_t new_offset = offset_;
861 offset_ += map_size;
862 return new_offset;
863 });
864 // Code offset is not initialized yet, so set the map offset to 0u-offset.
865 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
866 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100867 }
868 ++method_offsets_index_;
869 }
870
871 return true;
872 }
873
874 private:
875 // Deduplication is already done on a pointer basis by the compiler driver,
876 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100877 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100878};
879
880class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
881 public:
882 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800883 : OatDexMethodVisitor(writer, offset),
884 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100885 }
886
887 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700888 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800889 const DexFile::TypeId& type_id =
890 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
891 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
892 // Skip methods that are not in the image.
893 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
894 return true;
895 }
896
Vladimir Marko49b0f452015-12-10 13:49:19 +0000897 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100898 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
899
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800900 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100901 if (compiled_method != nullptr) {
902 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
903 offsets = oat_class->method_offsets_[method_offsets_index_];
904 ++method_offsets_index_;
905 }
906
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100907 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100908 // Unchecked as we hold mutator_lock_ on entry.
909 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800910 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700911 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
912 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800913 ArtMethod* method;
914 if (writer_->HasBootImage()) {
915 const InvokeType invoke_type = it.GetMethodInvokeType(
916 dex_file_->GetClassDef(class_def_index_));
917 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
918 *dex_file_,
919 it.GetMemberIndex(),
920 dex_cache,
921 ScopedNullHandle<mirror::ClassLoader>(),
922 nullptr,
923 invoke_type);
924 if (method == nullptr) {
925 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
926 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
927 soa.Self()->AssertPendingException();
928 mirror::Throwable* exc = soa.Self()->GetException();
929 std::string dump = exc->Dump();
930 LOG(FATAL) << dump;
931 UNREACHABLE();
932 }
933 } else {
934 // Should already have been resolved by the compiler, just peek into the dex cache.
935 // It may not be resolved if the class failed to verify, in this case, don't set the
936 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
937 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700938 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800939 if (method != nullptr &&
940 compiled_method != nullptr &&
941 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100942 method->SetEntryPointFromQuickCompiledCodePtrSize(
943 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
944 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100945
946 return true;
947 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800948
949 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -0700950 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100951};
952
953class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
954 public:
955 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100956 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100957 : OatDexMethodVisitor(writer, relative_offset),
958 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100959 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100960 soa_(Thread::Current()),
961 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100962 class_linker_(Runtime::Current()->GetClassLinker()),
963 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100964 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800965 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100966 // If we're creating the image, the address space must be ready so that we can apply patches.
967 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100968 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969 }
970
Vladimir Markof4da6752014-08-01 19:04:18 +0100971 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100972 }
973
974 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700975 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100976 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
977 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700978 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000979 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100980 }
981 return true;
982 }
983
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700984 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100985 bool result = OatDexMethodVisitor::EndClass();
986 if (oat_class_index_ == writer_->oat_classes_.size()) {
987 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000988 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100989 if (UNLIKELY(offset_ == 0u)) {
990 PLOG(ERROR) << "Failed to write final relative call thunks";
991 result = false;
992 }
993 }
994 return result;
995 }
996
997 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700998 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000999 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001000 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1001
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001002 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1003 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001004 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001005 size_t file_offset = file_offset_;
1006 OutputStream* out = out_;
1007
Vladimir Marko35831e82015-09-11 11:59:18 +01001008 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1009 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001010
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001011 // Deduplicate code arrays.
1012 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1013 if (method_offsets.code_offset_ > offset_) {
1014 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1015 if (offset_ == 0u) {
1016 ReportWriteFailure("relative call thunk", it);
1017 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001018 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001019 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1020 if (alignment_size != 0) {
1021 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001022 ReportWriteFailure("code alignment padding", it);
1023 return false;
1024 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001025 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001026 DCHECK_OFFSET_();
1027 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001028 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001029 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1030 DCHECK_EQ(method_offsets.code_offset_,
1031 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1032 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1033 const OatQuickMethodHeader& method_header =
1034 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001035 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001036 ReportWriteFailure("method header", it);
1037 return false;
1038 }
1039 writer_->size_method_header_ += sizeof(method_header);
1040 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001041 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001042
1043 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001044 patched_code_.assign(quick_code.begin(), quick_code.end());
1045 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001046 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001047 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001048 switch (patch.GetType()) {
1049 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001050 // NOTE: Relative calls across oat files are not supported.
1051 uint32_t target_offset = GetTargetOffset(patch);
1052 writer_->relative_patcher_->PatchCall(&patched_code_,
1053 literal_offset,
1054 offset_ + literal_offset,
1055 target_offset);
1056 break;
1057 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001058 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001059 uint32_t target_offset = GetDexCacheOffset(patch);
1060 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1061 patch,
1062 offset_ + literal_offset,
1063 target_offset);
1064 break;
1065 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001066 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001067 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1068 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1069 patch,
1070 offset_ + literal_offset,
1071 target_offset);
1072 break;
1073 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001074 case LinkerPatch::Type::kTypeRelative: {
1075 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1076 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1077 patch,
1078 offset_ + literal_offset,
1079 target_offset);
1080 break;
1081 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001082 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001083 uint32_t target_offset = GetTargetOffset(patch);
1084 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1085 break;
1086 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001087 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001088 ArtMethod* method = GetTargetMethod(patch);
1089 PatchMethodAddress(&patched_code_, literal_offset, method);
1090 break;
1091 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001092 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001093 mirror::String* string = GetTargetString(patch);
1094 PatchObjectAddress(&patched_code_, literal_offset, string);
1095 break;
1096 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001097 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001098 mirror::Class* type = GetTargetType(patch);
1099 PatchObjectAddress(&patched_code_, literal_offset, type);
1100 break;
1101 }
1102 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001103 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001104 break;
1105 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001106 }
1107 }
1108 }
1109
Vladimir Markoe079e212016-05-25 12:49:49 +01001110 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001111 ReportWriteFailure("method code", it);
1112 return false;
1113 }
1114 writer_->size_code_ += code_size;
1115 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001116 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001117 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001118 ++method_offsets_index_;
1119 }
1120
1121 return true;
1122 }
1123
1124 private:
1125 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001126 const size_t file_offset_;
1127 const ScopedObjectAccess soa_;
1128 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001129 ClassLinker* const class_linker_;
1130 mirror::DexCache* dex_cache_;
1131 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001132
1133 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1134 PLOG(ERROR) << "Failed to write " << what << " for "
1135 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1136 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001137
Mathieu Chartiere401d142015-04-22 13:56:20 -07001138 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001139 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001140 MethodReference ref = patch.TargetMethod();
1141 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001142 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1143 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001144 ArtMethod* method = dex_cache->GetResolvedMethod(
1145 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001146 CHECK(method != nullptr);
1147 return method;
1148 }
1149
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001150 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001151 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1152 // If there's no new compiled code, either we're compiling an app and the target method
1153 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001154 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001155 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001156 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001157 PointerSize size =
1158 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001159 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1160 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001161 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001162 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1163 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1164 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1165 target_offset = PointerToLowMemUInt32(oat_code_offset);
1166 } else {
1167 target_offset = target->IsNative()
1168 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1169 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1170 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001171 }
1172 return target_offset;
1173 }
1174
Vladimir Marko052164a2016-04-27 13:54:18 +01001175 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001176 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001177 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001178 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001179 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1180 }
1181
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001182 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001183 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001184 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1185 CHECK(type != nullptr);
1186 return type;
1187 }
1188
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001189 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001190 ScopedObjectAccessUnchecked soa(Thread::Current());
1191 StackHandleScope<1> hs(soa.Self());
1192 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1193 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1194 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1195 patch.TargetStringIndex(),
1196 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001197 DCHECK(string != nullptr);
1198 DCHECK(writer_->HasBootImage() ||
1199 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1200 return string;
1201 }
1202
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001203 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001204 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001205 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1206 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1207 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1208 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001209 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001210 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001211 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1212 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001213 }
1214 }
1215
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001216 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001217 DCHECK(writer_->HasBootImage());
1218 object = writer_->image_writer_->GetImageAddress(object);
1219 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1220 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1221 // TODO: Clean up offset types. The target offset must be treated as signed.
1222 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1223 }
1224
Vladimir Markof4da6752014-08-01 19:04:18 +01001225 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001226 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001227 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001228 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001229 } else {
1230 // NOTE: We're using linker patches for app->boot references when the image can
1231 // be relocated and therefore we need to emit .oat_patches. We're not using this
1232 // for app->app references, so check that the object is in the image space.
1233 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001234 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001235 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001236 uint32_t address = PointerToLowMemUInt32(object);
1237 DCHECK_LE(offset + 4, code->size());
1238 uint8_t* data = &(*code)[offset];
1239 data[0] = address & 0xffu;
1240 data[1] = (address >> 8) & 0xffu;
1241 data[2] = (address >> 16) & 0xffu;
1242 data[3] = (address >> 24) & 0xffu;
1243 }
1244
Mathieu Chartiere401d142015-04-22 13:56:20 -07001245 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001246 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001247 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001248 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001249 } else if (kIsDebugBuild) {
1250 // NOTE: We're using linker patches for app->boot references when the image can
1251 // be relocated and therefore we need to emit .oat_patches. We're not using this
1252 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001253 std::vector<gc::space::ImageSpace*> image_spaces =
1254 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1255 bool contains_method = false;
1256 for (gc::space::ImageSpace* image_space : image_spaces) {
1257 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1258 contains_method |=
1259 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1260 }
1261 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001262 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001263 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001264 uint32_t address = PointerToLowMemUInt32(method);
1265 DCHECK_LE(offset + 4, code->size());
1266 uint8_t* data = &(*code)[offset];
1267 data[0] = address & 0xffu;
1268 data[1] = (address >> 8) & 0xffu;
1269 data[2] = (address >> 16) & 0xffu;
1270 data[3] = (address >> 24) & 0xffu;
1271 }
1272
Vladimir Markof4da6752014-08-01 19:04:18 +01001273 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001274 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001275 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001276 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001277 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1278 // TODO: Clean up offset types.
1279 // The target_offset must be treated as signed for cross-oat patching.
1280 const void* target = reinterpret_cast<const void*>(
1281 writer_->image_writer_->GetOatDataBegin(oat_index) +
1282 static_cast<int32_t>(target_offset));
1283 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001284 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001285 DCHECK_LE(offset + 4, code->size());
1286 uint8_t* data = &(*code)[offset];
1287 data[0] = address & 0xffu;
1288 data[1] = (address >> 8) & 0xffu;
1289 data[2] = (address >> 16) & 0xffu;
1290 data[3] = (address >> 24) & 0xffu;
1291 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001292};
1293
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001294class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1295 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001296 WriteMapMethodVisitor(OatWriter* writer,
1297 OutputStream* out,
1298 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001299 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001300 : OatDexMethodVisitor(writer, relative_offset),
1301 out_(out),
1302 file_offset_(file_offset) {
1303 }
1304
1305 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001306 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001307 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1308
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001309 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001310 size_t file_offset = file_offset_;
1311 OutputStream* out = out_;
1312
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001313 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1314 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001315 ++method_offsets_index_;
1316
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001317 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1318 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1319 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1320 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1321
1322 if (map_offset != 0u) {
1323 // Transform map_offset to actual oat data offset.
1324 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1325 DCHECK_NE(map_offset, 0u);
1326 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1327
1328 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1329 size_t map_size = map.size() * sizeof(map[0]);
1330 if (map_offset == offset_) {
1331 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001332 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001333 ReportWriteFailure(it);
1334 return false;
1335 }
1336 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001337 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001338 }
1339 DCHECK_OFFSET_();
1340 }
1341
1342 return true;
1343 }
1344
1345 private:
1346 OutputStream* const out_;
1347 size_t const file_offset_;
1348
1349 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001350 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001351 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1352 }
1353};
1354
1355// Visit all methods from all classes in all dex files with the specified visitor.
1356bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1357 for (const DexFile* dex_file : *dex_files_) {
1358 const size_t class_def_count = dex_file->NumClassDefs();
1359 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1360 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1361 return false;
1362 }
1363 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001364 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001365 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001366 ClassDataItemIterator it(*dex_file, class_data);
1367 while (it.HasNextStaticField()) {
1368 it.Next();
1369 }
1370 while (it.HasNextInstanceField()) {
1371 it.Next();
1372 }
1373 size_t class_def_method_index = 0u;
1374 while (it.HasNextDirectMethod()) {
1375 if (!visitor->VisitMethod(class_def_method_index, it)) {
1376 return false;
1377 }
1378 ++class_def_method_index;
1379 it.Next();
1380 }
1381 while (it.HasNextVirtualMethod()) {
1382 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1383 return false;
1384 }
1385 ++class_def_method_index;
1386 it.Next();
1387 }
1388 }
1389 if (UNLIKELY(!visitor->EndClass())) {
1390 return false;
1391 }
1392 }
1393 }
1394 return true;
1395}
1396
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001397size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1398 const InstructionSetFeatures* instruction_set_features,
1399 uint32_t num_dex_files,
1400 SafeMap<std::string, std::string>* key_value_store) {
1401 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1402 oat_header_.reset(OatHeader::Create(instruction_set,
1403 instruction_set_features,
1404 num_dex_files,
1405 key_value_store));
1406 size_oat_header_ += sizeof(OatHeader);
1407 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001408 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001409}
1410
1411size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001412 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1413 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001414 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001415 oat_dex_file.offset_ = offset;
1416 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001417 }
1418 return offset;
1419}
1420
Brian Carlstrom389efb02012-01-11 12:06:26 -08001421size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001422 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 InitOatClassesMethodVisitor visitor(this, offset);
1424 bool success = VisitDexMethods(&visitor);
1425 CHECK(success);
1426 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001427
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001428 // Update oat_dex_files_.
1429 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001430 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1431 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001432 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001433 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001435 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001436 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001437 CHECK(oat_class_it == oat_classes_.end());
1438
1439 return offset;
1440}
1441
1442size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001443 InitMapMethodVisitor visitor(this, offset);
1444 bool success = VisitDexMethods(&visitor);
1445 DCHECK(success);
1446 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001447
Brian Carlstrome24fa612011-09-29 00:53:55 -07001448 return offset;
1449}
1450
1451size_t OatWriter::InitOatCode(size_t offset) {
1452 // calculate the offsets within OatHeader to executable code
1453 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001454 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001455 // required to be on a new page boundary
1456 offset = RoundUp(offset, kPageSize);
1457 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001458 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001459 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001460 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001461
Ian Rogers848871b2013-08-05 10:56:33 -07001462 #define DO_TRAMPOLINE(field, fn_name) \
1463 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001464 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1465 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001466 (field) = compiler_driver_->Create ## fn_name(); \
1467 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001468
Ian Rogers848871b2013-08-05 10:56:33 -07001469 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001470 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001471 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001472 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1473 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001474
Ian Rogers848871b2013-08-05 10:56:33 -07001475 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001476 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001477 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1478 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1479 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001480 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001481 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001482 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001483 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001484 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001485 return offset;
1486}
1487
1488size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001489 #define VISIT(VisitorType) \
1490 do { \
1491 VisitorType visitor(this, offset); \
1492 bool success = VisitDexMethods(&visitor); \
1493 DCHECK(success); \
1494 offset = visitor.GetOffset(); \
1495 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001496
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001497 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001498 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001499 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001500 }
Logan Chien8b977d32012-02-21 19:14:55 +08001501
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001502 #undef VISIT
1503
Brian Carlstrome24fa612011-09-29 00:53:55 -07001504 return offset;
1505}
1506
David Srbeckybc90fd02015-04-22 19:40:27 +01001507bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001508 CHECK(write_state_ == WriteState::kWriteRoData);
1509
Vladimir Markoe079e212016-05-25 12:49:49 +01001510 // Wrap out to update checksum with each write.
1511 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1512 out = &checksum_updating_out;
1513
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001514 if (!WriteClassOffsets(out)) {
1515 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001516 return false;
1517 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001518
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001519 if (!WriteClasses(out)) {
1520 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001521 return false;
1522 }
1523
Vladimir Markof4da6752014-08-01 19:04:18 +01001524 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001525 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001526 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001527 return false;
1528 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001529 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001530 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001531 relative_offset = WriteMaps(out, file_offset, relative_offset);
1532 if (relative_offset == 0) {
1533 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1534 return false;
1535 }
1536
David Srbeckybc90fd02015-04-22 19:40:27 +01001537 // Write padding.
1538 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1539 relative_offset += size_executable_offset_alignment_;
1540 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1541 size_t expected_file_offset = file_offset + relative_offset;
1542 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1543 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1544 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1545 return 0;
1546 }
1547 DCHECK_OFFSET();
1548
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001549 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001550 return true;
1551}
1552
1553bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001554 CHECK(write_state_ == WriteState::kWriteText);
1555
Vladimir Markoe079e212016-05-25 12:49:49 +01001556 // Wrap out to update checksum with each write.
1557 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1558 out = &checksum_updating_out;
1559
Vladimir Marko944da602016-02-19 12:27:55 +00001560 SetMultiOatRelativePatcherAdjustment();
1561
David Srbeckybc90fd02015-04-22 19:40:27 +01001562 const size_t file_offset = oat_data_offset_;
1563 size_t relative_offset = oat_header_->GetExecutableOffset();
1564 DCHECK_OFFSET();
1565
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001566 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001567 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001568 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001569 return false;
1570 }
1571
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001572 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1573 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001574 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001575 return false;
1576 }
1577
Vladimir Markof4da6752014-08-01 19:04:18 +01001578 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001579 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001580 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1581 return false;
1582 }
1583
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001584 if (kIsDebugBuild) {
1585 uint32_t size_total = 0;
1586 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001587 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1588 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001589
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001590 DO_STAT(size_dex_file_alignment_);
1591 DO_STAT(size_executable_offset_alignment_);
1592 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001593 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001594 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001595 DO_STAT(size_interpreter_to_interpreter_bridge_);
1596 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1597 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001598 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001599 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001600 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001601 DO_STAT(size_quick_to_interpreter_bridge_);
1602 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001603 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001604 DO_STAT(size_code_);
1605 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001606 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001607 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001608 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001609 DO_STAT(size_oat_dex_file_location_size_);
1610 DO_STAT(size_oat_dex_file_location_data_);
1611 DO_STAT(size_oat_dex_file_location_checksum_);
1612 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001613 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001614 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001615 DO_STAT(size_oat_lookup_table_alignment_);
1616 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001617 DO_STAT(size_oat_class_offsets_alignment_);
1618 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001619 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001620 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001621 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001622 DO_STAT(size_oat_class_method_offsets_);
1623 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001624
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001625 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001626 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001627 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001628 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001629
Vladimir Markof4da6752014-08-01 19:04:18 +01001630 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001631 CHECK_EQ(size_, relative_offset);
1632
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001633 write_state_ = WriteState::kWriteHeader;
1634 return true;
1635}
1636
1637bool OatWriter::WriteHeader(OutputStream* out,
1638 uint32_t image_file_location_oat_checksum,
1639 uintptr_t image_file_location_oat_begin,
1640 int32_t image_patch_delta) {
1641 CHECK(write_state_ == WriteState::kWriteHeader);
1642
1643 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1644 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1645 if (compiler_driver_->IsBootImage()) {
1646 CHECK_EQ(image_patch_delta, 0);
1647 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1648 } else {
1649 CHECK_ALIGNED(image_patch_delta, kPageSize);
1650 oat_header_->SetImagePatchDelta(image_patch_delta);
1651 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001652 oat_header_->UpdateChecksumWithHeaderData();
1653
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001654 const size_t file_offset = oat_data_offset_;
1655
1656 off_t current_offset = out->Seek(0, kSeekCurrent);
1657 if (current_offset == static_cast<off_t>(-1)) {
1658 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1659 return false;
1660 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001661 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001662 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1663 return false;
1664 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001665 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001666
1667 // Flush all other data before writing the header.
1668 if (!out->Flush()) {
1669 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1670 return false;
1671 }
1672 // Write the header.
1673 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001674 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001675 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1676 return false;
1677 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001678 // Flush the header data.
1679 if (!out->Flush()) {
1680 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001681 return false;
1682 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001683
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001684 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1685 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1686 return false;
1687 }
1688 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1689
1690 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001691 return true;
1692}
1693
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001694bool OatWriter::WriteClassOffsets(OutputStream* out) {
1695 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1696 if (oat_dex_file.class_offsets_offset_ != 0u) {
1697 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1698 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1699 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1700 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1701 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001702 return false;
1703 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001704 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1705 return false;
1706 }
1707 }
1708 }
1709 return true;
1710}
1711
1712bool OatWriter::WriteClasses(OutputStream* out) {
1713 for (OatClass& oat_class : oat_classes_) {
1714 if (!oat_class.Write(this, out, oat_data_offset_)) {
1715 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1716 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001717 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001718 }
1719 return true;
1720}
1721
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001722size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001723 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001724 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1725 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1726 return 0;
1727 }
1728 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001729 size_vmap_table_ = relative_offset - vmap_tables_offset;
1730
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001731 return relative_offset;
1732}
1733
1734size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001735 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001736 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001737
Ian Rogers848871b2013-08-05 10:56:33 -07001738 #define DO_TRAMPOLINE(field) \
1739 do { \
1740 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1741 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001742 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001743 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001744 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001745 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001746 return false; \
1747 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001748 size_ ## field += (field)->size(); \
1749 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001750 DCHECK_OFFSET(); \
1751 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001752
Ian Rogers848871b2013-08-05 10:56:33 -07001753 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001754 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001755 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001756 DO_TRAMPOLINE(quick_resolution_trampoline_);
1757 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1758 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001759 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001760 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001761}
1762
Ian Rogers3d504072014-03-01 09:16:49 -08001763size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001764 const size_t file_offset,
1765 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001766 #define VISIT(VisitorType) \
1767 do { \
1768 VisitorType visitor(this, out, file_offset, relative_offset); \
1769 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1770 return 0; \
1771 } \
1772 relative_offset = visitor.GetOffset(); \
1773 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001774
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001775 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001776
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001777 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001778
Vladimir Markob163bb72015-03-31 21:49:49 +01001779 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1780 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1781 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1782
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001783 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001784}
1785
Vladimir Marko944da602016-02-19 12:27:55 +00001786bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001787 // Get the elf file offset of the oat file.
1788 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1789 if (raw_file_offset == static_cast<off_t>(-1)) {
1790 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1791 return false;
1792 }
1793 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1794 return true;
1795}
1796
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001797bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1798 // Read the dex file header and perform minimal verification.
1799 uint8_t raw_header[sizeof(DexFile::Header)];
1800 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1801 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1802 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1803 return false;
1804 }
1805 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1806 return false;
1807 }
1808
1809 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1810 oat_dex_file->dex_file_size_ = header->file_size_;
1811 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1812 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1813 return true;
1814}
1815
1816bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1817 if (!DexFile::IsMagicValid(raw_header)) {
1818 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1819 return false;
1820 }
1821 if (!DexFile::IsVersionValid(raw_header)) {
1822 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1823 return false;
1824 }
1825 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1826 if (header->file_size_ < sizeof(DexFile::Header)) {
1827 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1828 << " File: " << location;
1829 return false;
1830 }
1831 return true;
1832}
1833
1834bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1835 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1836
1837 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001838 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001839 return false;
1840 }
1841
1842 // Write dex files.
1843 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1844 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1845 return false;
1846 }
1847 }
1848
1849 // Close sources.
1850 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1851 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1852 }
1853 zipped_dex_files_.clear();
1854 zip_archives_.clear();
1855 raw_dex_files_.clear();
1856 return true;
1857}
1858
1859bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1860 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1861 return false;
1862 }
1863 if (oat_dex_file->source_.IsZipEntry()) {
1864 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1865 return false;
1866 }
1867 } else if (oat_dex_file->source_.IsRawFile()) {
1868 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1869 return false;
1870 }
1871 } else {
1872 DCHECK(oat_dex_file->source_.IsRawData());
1873 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1874 return false;
1875 }
1876 }
1877
1878 // Update current size and account for the written data.
1879 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1880 size_ += oat_dex_file->dex_file_size_;
1881 size_dex_file_ += oat_dex_file->dex_file_size_;
1882 return true;
1883}
1884
1885bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1886 // Dex files are required to be 4 byte aligned.
1887 size_t original_offset = size_;
1888 size_t offset = RoundUp(original_offset, 4);
1889 size_dex_file_alignment_ += offset - original_offset;
1890
1891 // Seek to the start of the dex file and flush any pending operations in the stream.
1892 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1893 uint32_t start_offset = oat_data_offset_ + offset;
1894 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1895 if (actual_offset != static_cast<off_t>(start_offset)) {
1896 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1897 << " Expected: " << start_offset
1898 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1899 return false;
1900 }
1901 if (!out->Flush()) {
1902 PLOG(ERROR) << "Failed to flush before writing dex file."
1903 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1904 return false;
1905 }
1906 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1907 if (actual_offset != static_cast<off_t>(start_offset)) {
1908 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1909 << " Expected: " << start_offset
1910 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1911 return false;
1912 }
1913
1914 size_ = offset;
1915 oat_dex_file->dex_file_offset_ = offset;
1916 return true;
1917}
1918
1919bool OatWriter::WriteDexFile(OutputStream* rodata,
1920 File* file,
1921 OatDexFile* oat_dex_file,
1922 ZipEntry* dex_file) {
1923 size_t start_offset = oat_data_offset_ + size_;
1924 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1925
1926 // Extract the dex file and get the extracted size.
1927 std::string error_msg;
1928 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1929 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1930 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1931 return false;
1932 }
1933 if (file->Flush() != 0) {
1934 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1935 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1936 return false;
1937 }
1938 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1939 if (extracted_end == static_cast<off_t>(-1)) {
1940 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1941 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1942 return false;
1943 }
1944 if (extracted_end < static_cast<off_t>(start_offset)) {
1945 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1946 << " Start: " << start_offset
1947 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1948 return false;
1949 }
1950 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1951 if (extracted_size < sizeof(DexFile::Header)) {
1952 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1953 << extracted_size << " File: " << oat_dex_file->GetLocation();
1954 return false;
1955 }
1956
1957 // Read the dex file header and extract required data to OatDexFile.
1958 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1959 if (actual_offset != static_cast<off_t>(start_offset)) {
1960 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1961 << " Expected: " << start_offset
1962 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1963 return false;
1964 }
1965 if (!ReadDexFileHeader(file, oat_dex_file)) {
1966 return false;
1967 }
1968 if (extracted_size < oat_dex_file->dex_file_size_) {
1969 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1970 << " file size from header: " << oat_dex_file->dex_file_size_
1971 << " File: " << oat_dex_file->GetLocation();
1972 return false;
1973 }
1974
1975 // Override the checksum from header with the CRC from ZIP entry.
1976 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1977
1978 // Seek both file and stream to the end offset.
1979 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1980 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1981 if (actual_offset != static_cast<off_t>(end_offset)) {
1982 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1983 << " Expected: " << end_offset
1984 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1985 return false;
1986 }
1987 actual_offset = rodata->Seek(end_offset, kSeekSet);
1988 if (actual_offset != static_cast<off_t>(end_offset)) {
1989 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1990 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1991 return false;
1992 }
1993 if (!rodata->Flush()) {
1994 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1995 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1996 return false;
1997 }
1998
1999 // If we extracted more than the size specified in the header, truncate the file.
2000 if (extracted_size > oat_dex_file->dex_file_size_) {
2001 if (file->SetLength(end_offset) != 0) {
2002 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2003 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2004 return false;
2005 }
2006 }
2007
2008 return true;
2009}
2010
2011bool OatWriter::WriteDexFile(OutputStream* rodata,
2012 File* file,
2013 OatDexFile* oat_dex_file,
2014 File* dex_file) {
2015 size_t start_offset = oat_data_offset_ + size_;
2016 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2017
2018 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2019 if (input_offset != static_cast<off_t>(0)) {
2020 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2021 << " Expected: 0"
2022 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2023 return false;
2024 }
2025 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2026 return false;
2027 }
2028
2029 // Copy the input dex file using sendfile().
2030 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2031 PLOG(ERROR) << "Failed to copy dex file to oat file."
2032 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2033 return false;
2034 }
2035 if (file->Flush() != 0) {
2036 PLOG(ERROR) << "Failed to flush dex file."
2037 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2038 return false;
2039 }
2040
2041 // Check file position and seek the stream to the end offset.
2042 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2043 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2044 if (actual_offset != static_cast<off_t>(end_offset)) {
2045 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2046 << " Expected: " << end_offset
2047 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2048 return false;
2049 }
2050 actual_offset = rodata->Seek(end_offset, kSeekSet);
2051 if (actual_offset != static_cast<off_t>(end_offset)) {
2052 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2053 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2054 return false;
2055 }
2056 if (!rodata->Flush()) {
2057 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2058 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2059 return false;
2060 }
2061
2062 return true;
2063}
2064
2065bool OatWriter::WriteDexFile(OutputStream* rodata,
2066 OatDexFile* oat_dex_file,
2067 const uint8_t* dex_file) {
2068 // Note: The raw data has already been checked to contain the header
2069 // and all the data that the header specifies as the file size.
2070 DCHECK(dex_file != nullptr);
2071 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2072 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2073
Vladimir Markoe079e212016-05-25 12:49:49 +01002074 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002075 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2076 << " to " << rodata->GetLocation();
2077 return false;
2078 }
2079 if (!rodata->Flush()) {
2080 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2081 << " File: " << oat_dex_file->GetLocation();
2082 return false;
2083 }
2084
2085 // Update dex file size and resize class offsets in the OatDexFile.
2086 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2087 oat_dex_file->dex_file_size_ = header->file_size_;
2088 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2089 return true;
2090}
2091
2092bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2093 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2094
David Brazdil181e1cc2016-09-01 16:38:47 +00002095 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2096 if (initial_offset == static_cast<off_t>(-1)) {
2097 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2098 return false;
2099 }
2100
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002101 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2102 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2103 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2104 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2105 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2106 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2107 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2108 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2109 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2110 return false;
2111 }
2112
2113 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2114 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2115
2116 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2117 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2118
2119 // Write OatDexFile.
2120 if (!oat_dex_file->Write(this, rodata)) {
2121 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2122 return false;
2123 }
2124 }
2125
David Brazdil181e1cc2016-09-01 16:38:47 +00002126 // Seek back to the initial position.
2127 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2128 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2129 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2130 return false;
2131 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002132
David Brazdilb92ba622016-09-01 16:00:30 +00002133 return true;
2134}
2135
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002136bool OatWriter::OpenDexFiles(
2137 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002138 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002139 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2140 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2141 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2142
2143 if (oat_dex_files_.empty()) {
2144 // Nothing to do.
2145 return true;
2146 }
2147
2148 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2149 size_t length = size_ - map_offset;
2150 std::string error_msg;
2151 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2152 PROT_READ | PROT_WRITE,
2153 MAP_SHARED,
2154 file->Fd(),
2155 oat_data_offset_ + map_offset,
2156 /* low_4gb */ false,
2157 file->GetPath().c_str(),
2158 &error_msg));
2159 if (dex_files_map == nullptr) {
2160 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2161 << " error: " << error_msg;
2162 return false;
2163 }
2164 std::vector<std::unique_ptr<const DexFile>> dex_files;
2165 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2166 // Make sure no one messed with input files while we were copying data.
2167 // At the very least we need consistent file size and number of class definitions.
2168 const uint8_t* raw_dex_file =
2169 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2170 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2171 // Note: ValidateDexFileHeader() already logged an error message.
2172 LOG(ERROR) << "Failed to verify written dex file header!"
2173 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2174 << " ~ " << static_cast<const void*>(raw_dex_file);
2175 return false;
2176 }
2177 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2178 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2179 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2180 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2181 << " Output: " << file->GetPath();
2182 return false;
2183 }
2184 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2185 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2186 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2187 << " Output: " << file->GetPath();
2188 return false;
2189 }
2190
2191 // Now, open the dex file.
2192 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2193 oat_dex_file.dex_file_size_,
2194 oat_dex_file.GetLocation(),
2195 oat_dex_file.dex_file_location_checksum_,
2196 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002197 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002198 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002199 &error_msg));
2200 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002201 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2202 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002203 return false;
2204 }
2205 }
2206
2207 *opened_dex_files_map = std::move(dex_files_map);
2208 *opened_dex_files = std::move(dex_files);
2209 return true;
2210}
2211
2212bool OatWriter::WriteTypeLookupTables(
David Brazdil181e1cc2016-09-01 16:38:47 +00002213 OutputStream* rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002214 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2215 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2216
2217 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2218 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2219 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002220 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2221
2222 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2223 oat_dex_file->class_offsets_.empty()) {
2224 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002225 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002226
2227 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2228 if (table_size == 0u) {
2229 continue;
2230 }
2231
2232 // Create the lookup table. When `nullptr` is given as the storage buffer,
2233 // TypeLookupTable allocates its own and DexFile takes ownership.
2234 opened_dex_files[i]->CreateTypeLookupTable(/* storage */ nullptr);
2235 TypeLookupTable* table = opened_dex_files[i]->GetTypeLookupTable();
2236
2237 // Type tables are required to be 4 byte aligned.
2238 size_t original_offset = size_;
2239 size_t rodata_offset = RoundUp(original_offset, 4);
2240 size_t padding_size = rodata_offset - original_offset;
2241
2242 if (padding_size != 0u) {
2243 std::vector<uint8_t> buffer(padding_size, 0u);
2244 if (!rodata->WriteFully(buffer.data(), padding_size)) {
2245 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2246 << " File: " << oat_dex_file->GetLocation()
2247 << " Output: " << rodata->GetLocation();
2248 return false;
2249 }
2250 }
2251
2252 DCHECK_EQ(oat_data_offset_ + rodata_offset,
2253 static_cast<size_t>(rodata->Seek(0u, kSeekCurrent)));
2254 DCHECK_EQ(table_size, table->RawDataLength());
2255
2256 if (!rodata->WriteFully(table->RawData(), table_size)) {
2257 PLOG(ERROR) << "Failed to write lookup table."
2258 << " File: " << oat_dex_file->GetLocation()
2259 << " Output: " << rodata->GetLocation();
2260 return false;
2261 }
2262
2263 oat_dex_file->lookup_table_offset_ = rodata_offset;
2264
2265 size_ += padding_size + table_size;
2266 size_oat_lookup_table_ += table_size;
2267 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002268 }
2269
David Brazdil181e1cc2016-09-01 16:38:47 +00002270 if (!rodata->Flush()) {
2271 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
2272 << " File: " << rodata->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002273 return false;
2274 }
2275
2276 return true;
2277}
2278
Vladimir Markof4da6752014-08-01 19:04:18 +01002279bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2280 static const uint8_t kPadding[] = {
2281 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2282 };
2283 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002284 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002285 return false;
2286 }
2287 size_code_alignment_ += aligned_code_delta;
2288 return true;
2289}
2290
Vladimir Marko944da602016-02-19 12:27:55 +00002291void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2292 DCHECK(dex_files_ != nullptr);
2293 DCHECK(relative_patcher_ != nullptr);
2294 DCHECK_NE(oat_data_offset_, 0u);
2295 if (image_writer_ != nullptr && !dex_files_->empty()) {
2296 // The oat data begin may not be initialized yet but the oat file offset is ready.
2297 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2298 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2299 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002300 }
2301}
2302
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002303OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2304 DexFileSource source,
2305 CreateTypeLookupTable create_type_lookup_table)
2306 : source_(source),
2307 create_type_lookup_table_(create_type_lookup_table),
2308 dex_file_size_(0),
2309 offset_(0),
2310 dex_file_location_size_(strlen(dex_file_location)),
2311 dex_file_location_data_(dex_file_location),
2312 dex_file_location_checksum_(0u),
2313 dex_file_offset_(0u),
2314 class_offsets_offset_(0u),
2315 lookup_table_offset_(0u),
2316 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002317}
2318
2319size_t OatWriter::OatDexFile::SizeOf() const {
2320 return sizeof(dex_file_location_size_)
2321 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002322 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002323 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002324 + sizeof(class_offsets_offset_)
2325 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002326}
2327
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002328void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2329 DCHECK_EQ(class_offsets_offset_, 0u);
2330 if (!class_offsets_.empty()) {
2331 // Class offsets are required to be 4 byte aligned.
2332 size_t original_offset = oat_writer->size_;
2333 size_t offset = RoundUp(original_offset, 4);
2334 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2335 class_offsets_offset_ = offset;
2336 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2337 }
2338}
2339
2340bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2341 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002342 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002343
Vladimir Markoe079e212016-05-25 12:49:49 +01002344 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002345 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002346 return false;
2347 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002348 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002349
Vladimir Markoe079e212016-05-25 12:49:49 +01002350 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002351 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002352 return false;
2353 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002354 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002355
Vladimir Markoe079e212016-05-25 12:49:49 +01002356 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002357 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002358 return false;
2359 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002360 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002361
Vladimir Markoe079e212016-05-25 12:49:49 +01002362 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002363 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002364 return false;
2365 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002366 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367
Vladimir Markoe079e212016-05-25 12:49:49 +01002368 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002369 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2370 return false;
2371 }
2372 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2373
Vladimir Markoe079e212016-05-25 12:49:49 +01002374 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002375 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2376 return false;
2377 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002378 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002379
2380 return true;
2381}
2382
2383bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002384 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002385 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2386 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002387 return false;
2388 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002389 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002390 return true;
2391}
2392
Brian Carlstromba150c32013-08-27 17:31:03 -07002393OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002394 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002395 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002396 mirror::Class::Status status)
2397 : compiled_methods_(compiled_methods) {
2398 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002399 CHECK_LE(num_non_null_compiled_methods, num_methods);
2400
Brian Carlstrom265091e2013-01-30 14:08:26 -08002401 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002402 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2403
2404 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2405 // apply when there are 0 methods, we just arbitrarily say that 0
2406 // methods means kOatClassNoneCompiled and that we won't use
2407 // kOatClassAllCompiled unless there is at least one compiled
2408 // method. This means in an interpretter only system, we can assert
2409 // that all classes are kOatClassNoneCompiled.
2410 if (num_non_null_compiled_methods == 0) {
2411 type_ = kOatClassNoneCompiled;
2412 } else if (num_non_null_compiled_methods == num_methods) {
2413 type_ = kOatClassAllCompiled;
2414 } else {
2415 type_ = kOatClassSomeCompiled;
2416 }
2417
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002418 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002419 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002420 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002421
2422 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2423 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002424 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002425 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2426 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2427 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2428 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002429 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002430 method_bitmap_size_ = 0;
2431 }
2432
2433 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002434 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002435 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002436 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2437 } else {
2438 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2439 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2440 if (type_ == kOatClassSomeCompiled) {
2441 method_bitmap_->SetBit(i);
2442 }
2443 }
2444 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002445}
2446
Brian Carlstrom265091e2013-01-30 14:08:26 -08002447size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2448 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002449 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2450 if (method_offset == 0) {
2451 return 0;
2452 }
2453 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002454}
2455
2456size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2457 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002458 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002459}
2460
2461size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002462 return sizeof(status_)
2463 + sizeof(type_)
2464 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2465 + method_bitmap_size_
2466 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002467}
2468
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002469bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002470 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002471 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002472 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002473 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002474 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002475 return false;
2476 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002477 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002478
Vladimir Markoe079e212016-05-25 12:49:49 +01002479 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002480 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002481 return false;
2482 }
2483 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002484
Brian Carlstromba150c32013-08-27 17:31:03 -07002485 if (method_bitmap_size_ != 0) {
2486 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002487 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002488 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002489 return false;
2490 }
2491 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002492
Vladimir Markoe079e212016-05-25 12:49:49 +01002493 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002494 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002495 return false;
2496 }
2497 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2498 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002499
Vladimir Markoe079e212016-05-25 12:49:49 +01002500 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002501 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002502 return false;
2503 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002504 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002505 return true;
2506}
2507
Brian Carlstrome24fa612011-09-29 00:53:55 -07002508} // namespace art