blob: 8273b1566755ca4b4b7e6c9f984da852daeda473 [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
229 void ReserveTypeLookupTable(OatWriter* oat_writer);
230 void ReserveClassOffsets(OatWriter* oat_writer);
231
Vladimir Marko49b0f452015-12-10 13:49:19 +0000232 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000233 bool Write(OatWriter* oat_writer, OutputStream* out) const;
234 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
235
236 // The source of the dex file.
237 DexFileSource source_;
238
239 // Whether to create the type lookup table.
240 CreateTypeLookupTable create_type_lookup_table_;
241
242 // Dex file size. Initialized when writing the dex file.
243 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000244
245 // Offset of start of OatDexFile from beginning of OatHeader. It is
246 // used to validate file position when writing.
247 size_t offset_;
248
249 // Data to write.
250 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000251 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000252 uint32_t dex_file_location_checksum_;
253 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000254 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000255 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000256
257 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000258 dchecked_vector<uint32_t> class_offsets_;
259
260 private:
261 size_t GetClassOffsetsRawSize() const {
262 return class_offsets_.size() * sizeof(class_offsets_[0]);
263 }
264
265 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
266};
267
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100268#define DCHECK_OFFSET() \
269 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
270 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
271
272#define DCHECK_OFFSET_() \
273 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
274 << "file_offset=" << file_offset << " offset_=" << offset_
275
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000276OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
277 : write_state_(WriteState::kAddingDexFileSources),
278 timings_(timings),
279 raw_dex_files_(),
280 zip_archives_(),
281 zipped_dex_files_(),
282 zipped_dex_file_locations_(),
283 compiler_driver_(nullptr),
284 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800285 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000286 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100287 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000288 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100289 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700290 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700291 size_dex_file_alignment_(0),
292 size_executable_offset_alignment_(0),
293 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700294 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700295 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700296 size_interpreter_to_interpreter_bridge_(0),
297 size_interpreter_to_compiled_code_bridge_(0),
298 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800299 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700300 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700301 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700302 size_quick_to_interpreter_bridge_(0),
303 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100304 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700305 size_code_(0),
306 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100307 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100308 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700310 size_oat_dex_file_location_size_(0),
311 size_oat_dex_file_location_data_(0),
312 size_oat_dex_file_location_checksum_(0),
313 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000314 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000315 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000316 size_oat_lookup_table_alignment_(0),
317 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000318 size_oat_class_offsets_alignment_(0),
319 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700320 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700321 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700322 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100323 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000324 relative_patcher_(nullptr),
325 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000326}
327
328bool OatWriter::AddDexFileSource(const char* filename,
329 const char* location,
330 CreateTypeLookupTable create_type_lookup_table) {
331 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
332 uint32_t magic;
333 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700334 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
335 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000336 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
337 return false;
338 } else if (IsDexMagic(magic)) {
339 // The file is open for reading, not writing, so it's OK to let the File destructor
340 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700341 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000342 oat_dex_files_.emplace_back(location,
343 DexFileSource(raw_dex_files_.back().get()),
344 create_type_lookup_table);
345 } else if (IsZipMagic(magic)) {
346 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
347 return false;
348 }
349 } else {
350 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
351 return false;
352 }
353 return true;
354}
355
356// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700357bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000358 const char* location,
359 CreateTypeLookupTable create_type_lookup_table) {
360 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
361 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700362 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000363 ZipArchive* zip_archive = zip_archives_.back().get();
364 if (zip_archive == nullptr) {
365 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
366 << error_msg;
367 return false;
368 }
369 for (size_t i = 0; ; ++i) {
370 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
371 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
372 if (entry == nullptr) {
373 break;
374 }
375 zipped_dex_files_.push_back(std::move(entry));
376 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
377 const char* full_location = zipped_dex_file_locations_.back().c_str();
378 oat_dex_files_.emplace_back(full_location,
379 DexFileSource(zipped_dex_files_.back().get()),
380 create_type_lookup_table);
381 }
382 if (zipped_dex_file_locations_.empty()) {
383 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
384 return false;
385 }
386 return true;
387}
388
389// Add dex file source from raw memory.
390bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
391 const char* location,
392 uint32_t location_checksum,
393 CreateTypeLookupTable create_type_lookup_table) {
394 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
395 if (data.size() < sizeof(DexFile::Header)) {
396 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
397 << data.size() << " File: " << location;
398 return false;
399 }
400 if (!ValidateDexFileHeader(data.data(), location)) {
401 return false;
402 }
403 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
404 if (data.size() < header->file_size_) {
405 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
406 << " file size from header: " << header->file_size_ << " File: " << location;
407 return false;
408 }
409
410 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
411 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
412 return true;
413}
414
415dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
416 dchecked_vector<const char*> locations;
417 locations.reserve(oat_dex_files_.size());
418 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
419 locations.push_back(oat_dex_file.GetLocation());
420 }
421 return locations;
422}
423
424bool OatWriter::WriteAndOpenDexFiles(
425 OutputStream* rodata,
426 File* file,
427 InstructionSet instruction_set,
428 const InstructionSetFeatures* instruction_set_features,
429 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800430 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000431 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
432 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
433 CHECK(write_state_ == WriteState::kAddingDexFileSources);
434
435 size_t offset = InitOatHeader(instruction_set,
436 instruction_set_features,
437 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
438 key_value_store);
439 offset = InitOatDexFiles(offset);
440 size_ = offset;
441
442 std::unique_ptr<MemMap> dex_files_map;
443 std::vector<std::unique_ptr<const DexFile>> dex_files;
444 if (!WriteDexFiles(rodata, file)) {
445 return false;
446 }
447 // Reserve space for type lookup tables and update type_lookup_table_offset_.
448 for (OatDexFile& oat_dex_file : oat_dex_files_) {
449 oat_dex_file.ReserveTypeLookupTable(this);
450 }
451 size_t size_after_type_lookup_tables = size_;
452 // Reserve space for class offsets and update class_offsets_offset_.
453 for (OatDexFile& oat_dex_file : oat_dex_files_) {
454 oat_dex_file.ReserveClassOffsets(this);
455 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100456 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
457 if (!WriteOatDexFiles(&checksum_updating_rodata) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000458 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800459 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000460 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
461 return false;
462 }
463
Vladimir Markoe079e212016-05-25 12:49:49 +0100464 // Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
465 // piece would be difficult because we're not using the OutpuStream directly.
466 if (!oat_dex_files_.empty()) {
467 size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
468 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
469 }
470
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000471 *opened_dex_files_map = std::move(dex_files_map);
472 *opened_dex_files = std::move(dex_files);
473 write_state_ = WriteState::kPrepareLayout;
474 return true;
475}
476
477void OatWriter::PrepareLayout(const CompilerDriver* compiler,
478 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000479 const std::vector<const DexFile*>& dex_files,
480 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 CHECK(write_state_ == WriteState::kPrepareLayout);
482
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000483 compiler_driver_ = compiler;
484 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000485 dex_files_ = &dex_files;
486 relative_patcher_ = relative_patcher;
487 SetMultiOatRelativePatcherAdjustment();
488
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 if (compiling_boot_image_) {
490 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800491 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100492 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100494
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800496 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800498 offset = InitOatClasses(offset);
499 }
500 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000501 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100502 offset = InitOatMaps(offset);
503 }
504 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000505 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800506 offset = InitOatCode(offset);
507 }
508 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000509 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800510 offset = InitOatCodeDexFiles(offset);
511 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700512 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700513
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800514 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100515 // Allocate space for app dex cache arrays in the .bss section.
516 size_t bss_start = RoundUp(size_, kPageSize);
Andreas Gampe542451c2016-07-26 09:02:02 -0700517 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100518 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000519 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100520 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
521 DexCacheArraysLayout layout(pointer_size, dex_file);
522 bss_size_ += layout.Size();
523 }
524 }
525
Brian Carlstrome24fa612011-09-29 00:53:55 -0700526 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800527 if (compiling_boot_image_) {
528 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000529 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800530 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000531
532 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700533}
534
Ian Rogers0571d352011-11-03 19:51:38 -0700535OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700536}
537
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100538class OatWriter::DexMethodVisitor {
539 public:
540 DexMethodVisitor(OatWriter* writer, size_t offset)
541 : writer_(writer),
542 offset_(offset),
543 dex_file_(nullptr),
544 class_def_index_(DexFile::kDexNoIndex) {
545 }
546
547 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
548 DCHECK(dex_file_ == nullptr);
549 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
550 dex_file_ = dex_file;
551 class_def_index_ = class_def_index;
552 return true;
553 }
554
555 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
556
557 virtual bool EndClass() {
558 if (kIsDebugBuild) {
559 dex_file_ = nullptr;
560 class_def_index_ = DexFile::kDexNoIndex;
561 }
562 return true;
563 }
564
565 size_t GetOffset() const {
566 return offset_;
567 }
568
569 protected:
570 virtual ~DexMethodVisitor() { }
571
572 OatWriter* const writer_;
573
574 // The offset is usually advanced for each visited method by the derived class.
575 size_t offset_;
576
577 // The dex file and class def index are set in StartClass().
578 const DexFile* dex_file_;
579 size_t class_def_index_;
580};
581
582class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
583 public:
584 OatDexMethodVisitor(OatWriter* writer, size_t offset)
585 : DexMethodVisitor(writer, offset),
586 oat_class_index_(0u),
587 method_offsets_index_(0u) {
588 }
589
590 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
591 DexMethodVisitor::StartClass(dex_file, class_def_index);
592 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
593 method_offsets_index_ = 0u;
594 return true;
595 }
596
597 bool EndClass() {
598 ++oat_class_index_;
599 return DexMethodVisitor::EndClass();
600 }
601
602 protected:
603 size_t oat_class_index_;
604 size_t method_offsets_index_;
605};
606
607class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
608 public:
609 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
610 : DexMethodVisitor(writer, offset),
611 compiled_methods_(),
612 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000613 size_t num_classes = 0u;
614 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
615 num_classes += oat_dex_file.class_offsets_.size();
616 }
617 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100618 compiled_methods_.reserve(256u);
619 }
620
621 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
622 DexMethodVisitor::StartClass(dex_file, class_def_index);
623 compiled_methods_.clear();
624 num_non_null_compiled_methods_ = 0u;
625 return true;
626 }
627
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300628 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
629 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100630 // Fill in the compiled_methods_ array for methods that have a
631 // CompiledMethod. We track the number of non-null entries in
632 // num_non_null_compiled_methods_ since we only want to allocate
633 // OatMethodOffsets for the compiled methods.
634 uint32_t method_idx = it.GetMemberIndex();
635 CompiledMethod* compiled_method =
636 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
637 compiled_methods_.push_back(compiled_method);
638 if (compiled_method != nullptr) {
639 ++num_non_null_compiled_methods_;
640 }
641 return true;
642 }
643
644 bool EndClass() {
645 ClassReference class_ref(dex_file_, class_def_index_);
646 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
647 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700648 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100649 status = compiled_class->GetStatus();
650 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
651 status = mirror::Class::kStatusError;
652 } else {
653 status = mirror::Class::kStatusNotReady;
654 }
655
Vladimir Marko49b0f452015-12-10 13:49:19 +0000656 writer_->oat_classes_.emplace_back(offset_,
657 compiled_methods_,
658 num_non_null_compiled_methods_,
659 status);
660 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100661 return DexMethodVisitor::EndClass();
662 }
663
664 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000665 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100666 size_t num_non_null_compiled_methods_;
667};
668
669class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
670 public:
671 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100672 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100673 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100674 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100675 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
676 }
677
678 bool EndClass() {
679 OatDexMethodVisitor::EndClass();
680 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100681 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100682 }
683 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100684 }
685
686 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700687 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000688 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100689 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
690
691 if (compiled_method != nullptr) {
692 // Derived from CompiledMethod.
693 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100694
Vladimir Marko35831e82015-09-11 11:59:18 +0100695 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
696 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800697 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800698
David Srbecky009e2a62015-04-15 02:46:30 +0100699 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100700 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800701 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000702 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000703 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
704 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800705 // Duplicate methods, we want the same code for both of them so that the oat writer puts
706 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800707 } else {
708 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100709 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800710 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000711 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100712 quick_code_offset = dedupe_map_.GetOrCreate(
713 compiled_method,
714 [this, &deduped, compiled_method, &it, thumb_offset]() {
715 deduped = false;
716 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
717 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800718 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100719
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100720 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000721 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100722 // TODO: Should this be a hard failure?
723 LOG(WARNING) << "Multiple definitions of "
724 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000725 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
726 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100727 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000728 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100729 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800730 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100731
Elliott Hughes956af0f2014-12-11 14:34:28 -0800732 // Update quick method header.
733 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
734 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800735 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100736 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
737 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100738 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800739 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
740 // to 0-offset and we need to adjust it by code_offset.
741 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100742 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800743 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100744 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800745 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800746 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
747 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
748 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100749 *method_header = OatQuickMethodHeader(vmap_table_offset,
750 frame_size_in_bytes,
751 core_spill_mask,
752 fp_spill_mask,
753 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100754
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000755 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800756 // Update offsets. (Checksum is updated when writing.)
757 offset_ += sizeof(*method_header); // Method header is prepended before code.
758 offset_ += code_size;
759 // Record absolute patch locations.
760 if (!compiled_method->GetPatches().empty()) {
761 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
762 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000763 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100764 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100765 }
766 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100767 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800768 }
Alex Light78382fa2014-06-06 15:45:32 -0700769
David Srbecky91cc06c2016-03-07 16:13:58 +0000770 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000771 // Exclude quickened dex methods (code_size == 0) since they have no native code.
772 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
773 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800774 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000775 debug::MethodDebugInfo info = debug::MethodDebugInfo();
776 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000777 info.dex_file = dex_file_;
778 info.class_def_index = class_def_index_;
779 info.dex_method_index = it.GetMemberIndex();
780 info.access_flags = it.GetMethodAccessFlags();
781 info.code_item = it.GetMethodCodeItem();
782 info.isa = compiled_method->GetInstructionSet();
783 info.deduped = deduped;
784 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
785 info.is_optimized = method_header->IsOptimized();
786 info.is_code_address_text_relative = true;
787 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
788 info.code_size = code_size;
789 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
790 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
791 info.cfi = compiled_method->GetCFIInfo();
792 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100793 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100795 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
796 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
797 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100798 ++method_offsets_index_;
799 }
800
801 return true;
802 }
803
804 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000805 struct CodeOffsetsKeyComparator {
806 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100807 // Code is deduplicated by CompilerDriver, compare only data pointers.
808 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
809 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000810 }
811 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100812 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
813 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000814 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100815 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
816 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000817 }
818 return false;
819 }
820 };
821
David Srbecky009e2a62015-04-15 02:46:30 +0100822 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
823 const ClassDataItemIterator& it,
824 uint32_t thumb_offset) {
825 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100826 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100827 offset_ += CodeAlignmentSize(offset_, *compiled_method);
828 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100829 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
830 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
831 }
832
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833 // Deduplication is already done on a pointer basis by the compiler driver,
834 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100835 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100836
David Srbecky009e2a62015-04-15 02:46:30 +0100837 // Cache of compiler's --debuggable option.
838 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100839};
840
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
842 public:
843 InitMapMethodVisitor(OatWriter* writer, size_t offset)
844 : OatDexMethodVisitor(writer, offset) {
845 }
846
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700847 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700848 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000849 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100850 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
851
852 if (compiled_method != nullptr) {
853 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100854 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100855
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100856 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100857 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100858 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100859 size_t offset = dedupe_map_.GetOrCreate(
860 map.data(),
861 [this, map_size]() {
862 uint32_t new_offset = offset_;
863 offset_ += map_size;
864 return new_offset;
865 });
866 // Code offset is not initialized yet, so set the map offset to 0u-offset.
867 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
868 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100869 }
870 ++method_offsets_index_;
871 }
872
873 return true;
874 }
875
876 private:
877 // Deduplication is already done on a pointer basis by the compiler driver,
878 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100879 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100880};
881
882class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
883 public:
884 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800885 : OatDexMethodVisitor(writer, offset),
886 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100887 }
888
889 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700890 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800891 const DexFile::TypeId& type_id =
892 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
893 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
894 // Skip methods that are not in the image.
895 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
896 return true;
897 }
898
Vladimir Marko49b0f452015-12-10 13:49:19 +0000899 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100900 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
901
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800902 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 if (compiled_method != nullptr) {
904 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
905 offsets = oat_class->method_offsets_[method_offsets_index_];
906 ++method_offsets_index_;
907 }
908
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100909 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100910 // Unchecked as we hold mutator_lock_ on entry.
911 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800912 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700913 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
914 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800915 ArtMethod* method;
916 if (writer_->HasBootImage()) {
917 const InvokeType invoke_type = it.GetMethodInvokeType(
918 dex_file_->GetClassDef(class_def_index_));
919 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
920 *dex_file_,
921 it.GetMemberIndex(),
922 dex_cache,
923 ScopedNullHandle<mirror::ClassLoader>(),
924 nullptr,
925 invoke_type);
926 if (method == nullptr) {
927 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
928 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
929 soa.Self()->AssertPendingException();
930 mirror::Throwable* exc = soa.Self()->GetException();
931 std::string dump = exc->Dump();
932 LOG(FATAL) << dump;
933 UNREACHABLE();
934 }
935 } else {
936 // Should already have been resolved by the compiler, just peek into the dex cache.
937 // It may not be resolved if the class failed to verify, in this case, don't set the
938 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
939 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700940 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800941 if (method != nullptr &&
942 compiled_method != nullptr &&
943 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100944 method->SetEntryPointFromQuickCompiledCodePtrSize(
945 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
946 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100947
948 return true;
949 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800950
951 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -0700952 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100953};
954
955class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
956 public:
957 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100958 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 : OatDexMethodVisitor(writer, relative_offset),
960 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100961 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100962 soa_(Thread::Current()),
963 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100964 class_linker_(Runtime::Current()->GetClassLinker()),
965 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100966 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800967 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100968 // If we're creating the image, the address space must be ready so that we can apply patches.
969 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100970 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100971 }
972
Vladimir Markof4da6752014-08-01 19:04:18 +0100973 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100974 }
975
976 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700977 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100978 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
979 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700980 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000981 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100982 }
983 return true;
984 }
985
Mathieu Chartier90443472015-07-16 20:32:27 -0700986 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100987 bool result = OatDexMethodVisitor::EndClass();
988 if (oat_class_index_ == writer_->oat_classes_.size()) {
989 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000990 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100991 if (UNLIKELY(offset_ == 0u)) {
992 PLOG(ERROR) << "Failed to write final relative call thunks";
993 result = false;
994 }
995 }
996 return result;
997 }
998
999 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -07001000 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001001 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001002 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1003
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001004 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1005 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001006 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001007 size_t file_offset = file_offset_;
1008 OutputStream* out = out_;
1009
Vladimir Marko35831e82015-09-11 11:59:18 +01001010 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1011 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001012
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001013 // Deduplicate code arrays.
1014 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1015 if (method_offsets.code_offset_ > offset_) {
1016 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1017 if (offset_ == 0u) {
1018 ReportWriteFailure("relative call thunk", it);
1019 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001020 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001021 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1022 if (alignment_size != 0) {
1023 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001024 ReportWriteFailure("code alignment padding", it);
1025 return false;
1026 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001027 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001028 DCHECK_OFFSET_();
1029 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001030 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001031 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1032 DCHECK_EQ(method_offsets.code_offset_,
1033 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1034 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1035 const OatQuickMethodHeader& method_header =
1036 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001037 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001038 ReportWriteFailure("method header", it);
1039 return false;
1040 }
1041 writer_->size_method_header_ += sizeof(method_header);
1042 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001043 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001044
1045 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001046 patched_code_.assign(quick_code.begin(), quick_code.end());
1047 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001048 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001049 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001050 switch (patch.GetType()) {
1051 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001052 // NOTE: Relative calls across oat files are not supported.
1053 uint32_t target_offset = GetTargetOffset(patch);
1054 writer_->relative_patcher_->PatchCall(&patched_code_,
1055 literal_offset,
1056 offset_ + literal_offset,
1057 target_offset);
1058 break;
1059 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001060 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001061 uint32_t target_offset = GetDexCacheOffset(patch);
1062 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1063 patch,
1064 offset_ + literal_offset,
1065 target_offset);
1066 break;
1067 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001068 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001069 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1070 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1071 patch,
1072 offset_ + literal_offset,
1073 target_offset);
1074 break;
1075 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001076 case LinkerPatch::Type::kTypeRelative: {
1077 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1078 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1079 patch,
1080 offset_ + literal_offset,
1081 target_offset);
1082 break;
1083 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001084 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001085 uint32_t target_offset = GetTargetOffset(patch);
1086 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1087 break;
1088 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001089 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001090 ArtMethod* method = GetTargetMethod(patch);
1091 PatchMethodAddress(&patched_code_, literal_offset, method);
1092 break;
1093 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001094 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001095 mirror::String* string = GetTargetString(patch);
1096 PatchObjectAddress(&patched_code_, literal_offset, string);
1097 break;
1098 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001099 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001100 mirror::Class* type = GetTargetType(patch);
1101 PatchObjectAddress(&patched_code_, literal_offset, type);
1102 break;
1103 }
1104 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001105 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001106 break;
1107 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001108 }
1109 }
1110 }
1111
Vladimir Markoe079e212016-05-25 12:49:49 +01001112 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001113 ReportWriteFailure("method code", it);
1114 return false;
1115 }
1116 writer_->size_code_ += code_size;
1117 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001118 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001119 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001120 ++method_offsets_index_;
1121 }
1122
1123 return true;
1124 }
1125
1126 private:
1127 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001128 const size_t file_offset_;
1129 const ScopedObjectAccess soa_;
1130 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001131 ClassLinker* const class_linker_;
1132 mirror::DexCache* dex_cache_;
1133 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001134
1135 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1136 PLOG(ERROR) << "Failed to write " << what << " for "
1137 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1138 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001139
Mathieu Chartiere401d142015-04-22 13:56:20 -07001140 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001141 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001142 MethodReference ref = patch.TargetMethod();
1143 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001144 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1145 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001146 ArtMethod* method = dex_cache->GetResolvedMethod(
1147 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001148 CHECK(method != nullptr);
1149 return method;
1150 }
1151
Mathieu Chartier90443472015-07-16 20:32:27 -07001152 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001153 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1154 // If there's no new compiled code, either we're compiling an app and the target method
1155 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001156 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001158 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001159 PointerSize size =
1160 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001161 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1162 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001163 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001164 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1165 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1166 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1167 target_offset = PointerToLowMemUInt32(oat_code_offset);
1168 } else {
1169 target_offset = target->IsNative()
1170 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1171 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1172 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001173 }
1174 return target_offset;
1175 }
1176
Vladimir Marko052164a2016-04-27 13:54:18 +01001177 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
1178 SHARED_REQUIRES(Locks::mutator_lock_) {
1179 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001180 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001181 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1182 }
1183
1184 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1185 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001186 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1187 CHECK(type != nullptr);
1188 return type;
1189 }
1190
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001191 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001192 mirror::DexCache* dex_cache = GetDexCache(patch.TargetStringDexFile());
1193 mirror::String* string = dex_cache->GetResolvedString(patch.TargetStringIndex());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001194 DCHECK(string != nullptr);
1195 DCHECK(writer_->HasBootImage() ||
1196 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1197 return string;
1198 }
1199
Mathieu Chartier90443472015-07-16 20:32:27 -07001200 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001201 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001202 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1203 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1204 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1205 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001206 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001207 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001208 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1209 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001210 }
1211 }
1212
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001213 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1214 DCHECK(writer_->HasBootImage());
1215 object = writer_->image_writer_->GetImageAddress(object);
1216 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1217 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1218 // TODO: Clean up offset types. The target offset must be treated as signed.
1219 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1220 }
1221
Vladimir Markof4da6752014-08-01 19:04:18 +01001222 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001223 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001224 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001225 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001226 } else {
1227 // NOTE: We're using linker patches for app->boot references when the image can
1228 // be relocated and therefore we need to emit .oat_patches. We're not using this
1229 // for app->app references, so check that the object is in the image space.
1230 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001231 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001232 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001233 uint32_t address = PointerToLowMemUInt32(object);
1234 DCHECK_LE(offset + 4, code->size());
1235 uint8_t* data = &(*code)[offset];
1236 data[0] = address & 0xffu;
1237 data[1] = (address >> 8) & 0xffu;
1238 data[2] = (address >> 16) & 0xffu;
1239 data[3] = (address >> 24) & 0xffu;
1240 }
1241
Mathieu Chartiere401d142015-04-22 13:56:20 -07001242 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001243 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001244 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001245 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001246 } else if (kIsDebugBuild) {
1247 // NOTE: We're using linker patches for app->boot references when the image can
1248 // be relocated and therefore we need to emit .oat_patches. We're not using this
1249 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001250 std::vector<gc::space::ImageSpace*> image_spaces =
1251 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1252 bool contains_method = false;
1253 for (gc::space::ImageSpace* image_space : image_spaces) {
1254 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1255 contains_method |=
1256 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1257 }
1258 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001259 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001260 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001261 uint32_t address = PointerToLowMemUInt32(method);
1262 DCHECK_LE(offset + 4, code->size());
1263 uint8_t* data = &(*code)[offset];
1264 data[0] = address & 0xffu;
1265 data[1] = (address >> 8) & 0xffu;
1266 data[2] = (address >> 16) & 0xffu;
1267 data[3] = (address >> 24) & 0xffu;
1268 }
1269
Vladimir Markof4da6752014-08-01 19:04:18 +01001270 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001271 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001272 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001273 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001274 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1275 // TODO: Clean up offset types.
1276 // The target_offset must be treated as signed for cross-oat patching.
1277 const void* target = reinterpret_cast<const void*>(
1278 writer_->image_writer_->GetOatDataBegin(oat_index) +
1279 static_cast<int32_t>(target_offset));
1280 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001281 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001282 DCHECK_LE(offset + 4, code->size());
1283 uint8_t* data = &(*code)[offset];
1284 data[0] = address & 0xffu;
1285 data[1] = (address >> 8) & 0xffu;
1286 data[2] = (address >> 16) & 0xffu;
1287 data[3] = (address >> 24) & 0xffu;
1288 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001289};
1290
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001291class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1292 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001293 WriteMapMethodVisitor(OatWriter* writer,
1294 OutputStream* out,
1295 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001296 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297 : OatDexMethodVisitor(writer, relative_offset),
1298 out_(out),
1299 file_offset_(file_offset) {
1300 }
1301
1302 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001303 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001304 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1305
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001306 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001307 size_t file_offset = file_offset_;
1308 OutputStream* out = out_;
1309
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001310 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1311 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001312 ++method_offsets_index_;
1313
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001314 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1315 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1316 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1317 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1318
1319 if (map_offset != 0u) {
1320 // Transform map_offset to actual oat data offset.
1321 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1322 DCHECK_NE(map_offset, 0u);
1323 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1324
1325 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1326 size_t map_size = map.size() * sizeof(map[0]);
1327 if (map_offset == offset_) {
1328 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001329 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001330 ReportWriteFailure(it);
1331 return false;
1332 }
1333 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001334 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001335 }
1336 DCHECK_OFFSET_();
1337 }
1338
1339 return true;
1340 }
1341
1342 private:
1343 OutputStream* const out_;
1344 size_t const file_offset_;
1345
1346 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001347 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001348 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1349 }
1350};
1351
1352// Visit all methods from all classes in all dex files with the specified visitor.
1353bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1354 for (const DexFile* dex_file : *dex_files_) {
1355 const size_t class_def_count = dex_file->NumClassDefs();
1356 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1357 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1358 return false;
1359 }
1360 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001361 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001362 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001363 ClassDataItemIterator it(*dex_file, class_data);
1364 while (it.HasNextStaticField()) {
1365 it.Next();
1366 }
1367 while (it.HasNextInstanceField()) {
1368 it.Next();
1369 }
1370 size_t class_def_method_index = 0u;
1371 while (it.HasNextDirectMethod()) {
1372 if (!visitor->VisitMethod(class_def_method_index, it)) {
1373 return false;
1374 }
1375 ++class_def_method_index;
1376 it.Next();
1377 }
1378 while (it.HasNextVirtualMethod()) {
1379 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1380 return false;
1381 }
1382 ++class_def_method_index;
1383 it.Next();
1384 }
1385 }
1386 if (UNLIKELY(!visitor->EndClass())) {
1387 return false;
1388 }
1389 }
1390 }
1391 return true;
1392}
1393
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001394size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1395 const InstructionSetFeatures* instruction_set_features,
1396 uint32_t num_dex_files,
1397 SafeMap<std::string, std::string>* key_value_store) {
1398 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1399 oat_header_.reset(OatHeader::Create(instruction_set,
1400 instruction_set_features,
1401 num_dex_files,
1402 key_value_store));
1403 size_oat_header_ += sizeof(OatHeader);
1404 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001405 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001406}
1407
1408size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001409 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1410 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001411 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001412 oat_dex_file.offset_ = offset;
1413 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001414 }
1415 return offset;
1416}
1417
Brian Carlstrom389efb02012-01-11 12:06:26 -08001418size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001419 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420 InitOatClassesMethodVisitor visitor(this, offset);
1421 bool success = VisitDexMethods(&visitor);
1422 CHECK(success);
1423 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001424
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001425 // Update oat_dex_files_.
1426 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001427 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1428 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001429 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001430 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001431 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001432 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001433 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434 CHECK(oat_class_it == oat_classes_.end());
1435
1436 return offset;
1437}
1438
1439size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001440 InitMapMethodVisitor visitor(this, offset);
1441 bool success = VisitDexMethods(&visitor);
1442 DCHECK(success);
1443 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001444
Brian Carlstrome24fa612011-09-29 00:53:55 -07001445 return offset;
1446}
1447
1448size_t OatWriter::InitOatCode(size_t offset) {
1449 // calculate the offsets within OatHeader to executable code
1450 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001451 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001452 // required to be on a new page boundary
1453 offset = RoundUp(offset, kPageSize);
1454 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001455 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001456 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001457 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001458
Ian Rogers848871b2013-08-05 10:56:33 -07001459 #define DO_TRAMPOLINE(field, fn_name) \
1460 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001461 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1462 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001463 (field) = compiler_driver_->Create ## fn_name(); \
1464 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465
Ian Rogers848871b2013-08-05 10:56:33 -07001466 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001467 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001468 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001469 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1470 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001471
Ian Rogers848871b2013-08-05 10:56:33 -07001472 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001473 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001474 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1475 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1476 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001477 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001478 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001479 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001480 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001481 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001482 return offset;
1483}
1484
1485size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001486 #define VISIT(VisitorType) \
1487 do { \
1488 VisitorType visitor(this, offset); \
1489 bool success = VisitDexMethods(&visitor); \
1490 DCHECK(success); \
1491 offset = visitor.GetOffset(); \
1492 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001493
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001494 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001495 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001496 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001497 }
Logan Chien8b977d32012-02-21 19:14:55 +08001498
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001499 #undef VISIT
1500
Brian Carlstrome24fa612011-09-29 00:53:55 -07001501 return offset;
1502}
1503
David Srbeckybc90fd02015-04-22 19:40:27 +01001504bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001505 CHECK(write_state_ == WriteState::kWriteRoData);
1506
Vladimir Markoe079e212016-05-25 12:49:49 +01001507 // Wrap out to update checksum with each write.
1508 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1509 out = &checksum_updating_out;
1510
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001511 if (!WriteClassOffsets(out)) {
1512 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001513 return false;
1514 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001515
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001516 if (!WriteClasses(out)) {
1517 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001518 return false;
1519 }
1520
Vladimir Markof4da6752014-08-01 19:04:18 +01001521 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001522 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001523 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1524 return false;
1525 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001526 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001527 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001528 relative_offset = WriteMaps(out, file_offset, relative_offset);
1529 if (relative_offset == 0) {
1530 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1531 return false;
1532 }
1533
David Srbeckybc90fd02015-04-22 19:40:27 +01001534 // Write padding.
1535 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1536 relative_offset += size_executable_offset_alignment_;
1537 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1538 size_t expected_file_offset = file_offset + relative_offset;
1539 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1540 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1541 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1542 return 0;
1543 }
1544 DCHECK_OFFSET();
1545
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001546 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001547 return true;
1548}
1549
1550bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001551 CHECK(write_state_ == WriteState::kWriteText);
1552
Vladimir Markoe079e212016-05-25 12:49:49 +01001553 // Wrap out to update checksum with each write.
1554 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1555 out = &checksum_updating_out;
1556
Vladimir Marko944da602016-02-19 12:27:55 +00001557 SetMultiOatRelativePatcherAdjustment();
1558
David Srbeckybc90fd02015-04-22 19:40:27 +01001559 const size_t file_offset = oat_data_offset_;
1560 size_t relative_offset = oat_header_->GetExecutableOffset();
1561 DCHECK_OFFSET();
1562
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001563 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001564 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001565 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001566 return false;
1567 }
1568
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001569 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1570 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001571 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001572 return false;
1573 }
1574
Vladimir Markof4da6752014-08-01 19:04:18 +01001575 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001576 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001577 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1578 return false;
1579 }
1580
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001581 if (kIsDebugBuild) {
1582 uint32_t size_total = 0;
1583 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001584 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1585 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001586
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001587 DO_STAT(size_dex_file_alignment_);
1588 DO_STAT(size_executable_offset_alignment_);
1589 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001590 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001591 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001592 DO_STAT(size_interpreter_to_interpreter_bridge_);
1593 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1594 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001595 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001596 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001597 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001598 DO_STAT(size_quick_to_interpreter_bridge_);
1599 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001600 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001601 DO_STAT(size_code_);
1602 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001603 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001604 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001605 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001606 DO_STAT(size_oat_dex_file_location_size_);
1607 DO_STAT(size_oat_dex_file_location_data_);
1608 DO_STAT(size_oat_dex_file_location_checksum_);
1609 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001610 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001611 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001612 DO_STAT(size_oat_lookup_table_alignment_);
1613 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001614 DO_STAT(size_oat_class_offsets_alignment_);
1615 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001616 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001617 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001618 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001619 DO_STAT(size_oat_class_method_offsets_);
1620 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001621
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001622 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001623 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001624 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001625 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001626
Vladimir Markof4da6752014-08-01 19:04:18 +01001627 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001628 CHECK_EQ(size_, relative_offset);
1629
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001630 write_state_ = WriteState::kWriteHeader;
1631 return true;
1632}
1633
1634bool OatWriter::WriteHeader(OutputStream* out,
1635 uint32_t image_file_location_oat_checksum,
1636 uintptr_t image_file_location_oat_begin,
1637 int32_t image_patch_delta) {
1638 CHECK(write_state_ == WriteState::kWriteHeader);
1639
1640 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1641 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1642 if (compiler_driver_->IsBootImage()) {
1643 CHECK_EQ(image_patch_delta, 0);
1644 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1645 } else {
1646 CHECK_ALIGNED(image_patch_delta, kPageSize);
1647 oat_header_->SetImagePatchDelta(image_patch_delta);
1648 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001649 oat_header_->UpdateChecksumWithHeaderData();
1650
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001651 const size_t file_offset = oat_data_offset_;
1652
1653 off_t current_offset = out->Seek(0, kSeekCurrent);
1654 if (current_offset == static_cast<off_t>(-1)) {
1655 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1656 return false;
1657 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001658 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001659 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1660 return false;
1661 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001662 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001663
1664 // Flush all other data before writing the header.
1665 if (!out->Flush()) {
1666 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1667 return false;
1668 }
1669 // Write the header.
1670 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001671 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001672 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1673 return false;
1674 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001675 // Flush the header data.
1676 if (!out->Flush()) {
1677 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001678 return false;
1679 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001680
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001681 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1682 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1683 return false;
1684 }
1685 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1686
1687 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001688 return true;
1689}
1690
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001691bool OatWriter::WriteClassOffsets(OutputStream* out) {
1692 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1693 if (oat_dex_file.class_offsets_offset_ != 0u) {
1694 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1695 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1696 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1697 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1698 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001699 return false;
1700 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001701 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1702 return false;
1703 }
1704 }
1705 }
1706 return true;
1707}
1708
1709bool OatWriter::WriteClasses(OutputStream* out) {
1710 for (OatClass& oat_class : oat_classes_) {
1711 if (!oat_class.Write(this, out, oat_data_offset_)) {
1712 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1713 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001714 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001715 }
1716 return true;
1717}
1718
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001719size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001720 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001721 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1722 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1723 return 0;
1724 }
1725 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001726 size_vmap_table_ = relative_offset - vmap_tables_offset;
1727
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001728 return relative_offset;
1729}
1730
1731size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001732 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001733 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001734
Ian Rogers848871b2013-08-05 10:56:33 -07001735 #define DO_TRAMPOLINE(field) \
1736 do { \
1737 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1738 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001739 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001740 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001741 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001742 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001743 return false; \
1744 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001745 size_ ## field += (field)->size(); \
1746 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001747 DCHECK_OFFSET(); \
1748 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001749
Ian Rogers848871b2013-08-05 10:56:33 -07001750 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001751 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001752 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001753 DO_TRAMPOLINE(quick_resolution_trampoline_);
1754 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1755 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001756 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001757 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001758}
1759
Ian Rogers3d504072014-03-01 09:16:49 -08001760size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001761 const size_t file_offset,
1762 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001763 #define VISIT(VisitorType) \
1764 do { \
1765 VisitorType visitor(this, out, file_offset, relative_offset); \
1766 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1767 return 0; \
1768 } \
1769 relative_offset = visitor.GetOffset(); \
1770 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001771
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001772 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001773
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001774 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001775
Vladimir Markob163bb72015-03-31 21:49:49 +01001776 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1777 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1778 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1779
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001780 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001781}
1782
Vladimir Marko944da602016-02-19 12:27:55 +00001783bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001784 // Get the elf file offset of the oat file.
1785 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1786 if (raw_file_offset == static_cast<off_t>(-1)) {
1787 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1788 return false;
1789 }
1790 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1791 return true;
1792}
1793
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001794bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1795 // Read the dex file header and perform minimal verification.
1796 uint8_t raw_header[sizeof(DexFile::Header)];
1797 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1798 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1799 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1800 return false;
1801 }
1802 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1803 return false;
1804 }
1805
1806 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1807 oat_dex_file->dex_file_size_ = header->file_size_;
1808 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1809 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1810 return true;
1811}
1812
1813bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1814 if (!DexFile::IsMagicValid(raw_header)) {
1815 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1816 return false;
1817 }
1818 if (!DexFile::IsVersionValid(raw_header)) {
1819 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1820 return false;
1821 }
1822 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1823 if (header->file_size_ < sizeof(DexFile::Header)) {
1824 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1825 << " File: " << location;
1826 return false;
1827 }
1828 return true;
1829}
1830
1831bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1832 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1833
1834 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001835 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001836 return false;
1837 }
1838
1839 // Write dex files.
1840 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1841 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1842 return false;
1843 }
1844 }
1845
1846 // Close sources.
1847 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1848 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1849 }
1850 zipped_dex_files_.clear();
1851 zip_archives_.clear();
1852 raw_dex_files_.clear();
1853 return true;
1854}
1855
1856bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1857 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1858 return false;
1859 }
1860 if (oat_dex_file->source_.IsZipEntry()) {
1861 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1862 return false;
1863 }
1864 } else if (oat_dex_file->source_.IsRawFile()) {
1865 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1866 return false;
1867 }
1868 } else {
1869 DCHECK(oat_dex_file->source_.IsRawData());
1870 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1871 return false;
1872 }
1873 }
1874
1875 // Update current size and account for the written data.
1876 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1877 size_ += oat_dex_file->dex_file_size_;
1878 size_dex_file_ += oat_dex_file->dex_file_size_;
1879 return true;
1880}
1881
1882bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1883 // Dex files are required to be 4 byte aligned.
1884 size_t original_offset = size_;
1885 size_t offset = RoundUp(original_offset, 4);
1886 size_dex_file_alignment_ += offset - original_offset;
1887
1888 // Seek to the start of the dex file and flush any pending operations in the stream.
1889 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1890 uint32_t start_offset = oat_data_offset_ + offset;
1891 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1892 if (actual_offset != static_cast<off_t>(start_offset)) {
1893 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1894 << " Expected: " << start_offset
1895 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1896 return false;
1897 }
1898 if (!out->Flush()) {
1899 PLOG(ERROR) << "Failed to flush before writing dex file."
1900 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1901 return false;
1902 }
1903 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1904 if (actual_offset != static_cast<off_t>(start_offset)) {
1905 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1906 << " Expected: " << start_offset
1907 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1908 return false;
1909 }
1910
1911 size_ = offset;
1912 oat_dex_file->dex_file_offset_ = offset;
1913 return true;
1914}
1915
1916bool OatWriter::WriteDexFile(OutputStream* rodata,
1917 File* file,
1918 OatDexFile* oat_dex_file,
1919 ZipEntry* dex_file) {
1920 size_t start_offset = oat_data_offset_ + size_;
1921 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1922
1923 // Extract the dex file and get the extracted size.
1924 std::string error_msg;
1925 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1926 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1927 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1928 return false;
1929 }
1930 if (file->Flush() != 0) {
1931 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1932 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1933 return false;
1934 }
1935 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1936 if (extracted_end == static_cast<off_t>(-1)) {
1937 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1938 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1939 return false;
1940 }
1941 if (extracted_end < static_cast<off_t>(start_offset)) {
1942 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1943 << " Start: " << start_offset
1944 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1945 return false;
1946 }
1947 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1948 if (extracted_size < sizeof(DexFile::Header)) {
1949 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1950 << extracted_size << " File: " << oat_dex_file->GetLocation();
1951 return false;
1952 }
1953
1954 // Read the dex file header and extract required data to OatDexFile.
1955 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1956 if (actual_offset != static_cast<off_t>(start_offset)) {
1957 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1958 << " Expected: " << start_offset
1959 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1960 return false;
1961 }
1962 if (!ReadDexFileHeader(file, oat_dex_file)) {
1963 return false;
1964 }
1965 if (extracted_size < oat_dex_file->dex_file_size_) {
1966 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1967 << " file size from header: " << oat_dex_file->dex_file_size_
1968 << " File: " << oat_dex_file->GetLocation();
1969 return false;
1970 }
1971
1972 // Override the checksum from header with the CRC from ZIP entry.
1973 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1974
1975 // Seek both file and stream to the end offset.
1976 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1977 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1978 if (actual_offset != static_cast<off_t>(end_offset)) {
1979 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1980 << " Expected: " << end_offset
1981 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1982 return false;
1983 }
1984 actual_offset = rodata->Seek(end_offset, kSeekSet);
1985 if (actual_offset != static_cast<off_t>(end_offset)) {
1986 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1987 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1988 return false;
1989 }
1990 if (!rodata->Flush()) {
1991 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1992 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1993 return false;
1994 }
1995
1996 // If we extracted more than the size specified in the header, truncate the file.
1997 if (extracted_size > oat_dex_file->dex_file_size_) {
1998 if (file->SetLength(end_offset) != 0) {
1999 PLOG(ERROR) << "Failed to truncate excessive dex file length."
2000 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2001 return false;
2002 }
2003 }
2004
2005 return true;
2006}
2007
2008bool OatWriter::WriteDexFile(OutputStream* rodata,
2009 File* file,
2010 OatDexFile* oat_dex_file,
2011 File* dex_file) {
2012 size_t start_offset = oat_data_offset_ + size_;
2013 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
2014
2015 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2016 if (input_offset != static_cast<off_t>(0)) {
2017 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2018 << " Expected: 0"
2019 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2020 return false;
2021 }
2022 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2023 return false;
2024 }
2025
2026 // Copy the input dex file using sendfile().
2027 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2028 PLOG(ERROR) << "Failed to copy dex file to oat file."
2029 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2030 return false;
2031 }
2032 if (file->Flush() != 0) {
2033 PLOG(ERROR) << "Failed to flush dex file."
2034 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2035 return false;
2036 }
2037
2038 // Check file position and seek the stream to the end offset.
2039 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2040 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2041 if (actual_offset != static_cast<off_t>(end_offset)) {
2042 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2043 << " Expected: " << end_offset
2044 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2045 return false;
2046 }
2047 actual_offset = rodata->Seek(end_offset, kSeekSet);
2048 if (actual_offset != static_cast<off_t>(end_offset)) {
2049 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2050 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2051 return false;
2052 }
2053 if (!rodata->Flush()) {
2054 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2055 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2056 return false;
2057 }
2058
2059 return true;
2060}
2061
2062bool OatWriter::WriteDexFile(OutputStream* rodata,
2063 OatDexFile* oat_dex_file,
2064 const uint8_t* dex_file) {
2065 // Note: The raw data has already been checked to contain the header
2066 // and all the data that the header specifies as the file size.
2067 DCHECK(dex_file != nullptr);
2068 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2069 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2070
Vladimir Markoe079e212016-05-25 12:49:49 +01002071 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002072 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2073 << " to " << rodata->GetLocation();
2074 return false;
2075 }
2076 if (!rodata->Flush()) {
2077 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2078 << " File: " << oat_dex_file->GetLocation();
2079 return false;
2080 }
2081
2082 // Update dex file size and resize class offsets in the OatDexFile.
2083 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2084 oat_dex_file->dex_file_size_ = header->file_size_;
2085 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2086 return true;
2087}
2088
2089bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2090 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2091
2092 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2093 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2094 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2095 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2096 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2097 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2098 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2099 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2100 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2101 return false;
2102 }
2103
2104 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2105 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2106
2107 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2108 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2109
2110 // Write OatDexFile.
2111 if (!oat_dex_file->Write(this, rodata)) {
2112 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2113 return false;
2114 }
2115 }
2116
2117 return true;
2118}
2119
2120bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2121 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2122
2123 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2124 if (file->SetLength(new_length) != 0) {
2125 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2126 << "File: " << file->GetPath();
2127 return false;
2128 }
2129 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2130 if (actual_offset != static_cast<off_t>(new_length)) {
2131 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2132 << " Actual: " << actual_offset << " Expected: " << new_length
2133 << " File: " << rodata->GetLocation();
2134 return false;
2135 }
2136 if (!rodata->Flush()) {
2137 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2138 << " File: " << rodata->GetLocation();
2139 return false;
2140 }
2141 return true;
2142}
2143
2144bool OatWriter::OpenDexFiles(
2145 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002146 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002147 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2148 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2149 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2150
2151 if (oat_dex_files_.empty()) {
2152 // Nothing to do.
2153 return true;
2154 }
2155
2156 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2157 size_t length = size_ - map_offset;
2158 std::string error_msg;
2159 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2160 PROT_READ | PROT_WRITE,
2161 MAP_SHARED,
2162 file->Fd(),
2163 oat_data_offset_ + map_offset,
2164 /* low_4gb */ false,
2165 file->GetPath().c_str(),
2166 &error_msg));
2167 if (dex_files_map == nullptr) {
2168 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2169 << " error: " << error_msg;
2170 return false;
2171 }
2172 std::vector<std::unique_ptr<const DexFile>> dex_files;
2173 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2174 // Make sure no one messed with input files while we were copying data.
2175 // At the very least we need consistent file size and number of class definitions.
2176 const uint8_t* raw_dex_file =
2177 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2178 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2179 // Note: ValidateDexFileHeader() already logged an error message.
2180 LOG(ERROR) << "Failed to verify written dex file header!"
2181 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2182 << " ~ " << static_cast<const void*>(raw_dex_file);
2183 return false;
2184 }
2185 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2186 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2187 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2188 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2189 << " Output: " << file->GetPath();
2190 return false;
2191 }
2192 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2193 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2194 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2195 << " Output: " << file->GetPath();
2196 return false;
2197 }
2198
2199 // Now, open the dex file.
2200 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2201 oat_dex_file.dex_file_size_,
2202 oat_dex_file.GetLocation(),
2203 oat_dex_file.dex_file_location_checksum_,
2204 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002205 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002206 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002207 &error_msg));
2208 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002209 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2210 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002211 return false;
2212 }
2213 }
2214
2215 *opened_dex_files_map = std::move(dex_files_map);
2216 *opened_dex_files = std::move(dex_files);
2217 return true;
2218}
2219
2220bool OatWriter::WriteTypeLookupTables(
2221 MemMap* opened_dex_files_map,
2222 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2223 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2224
2225 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2226 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2227 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2228 if (oat_dex_file->lookup_table_offset_ != 0u) {
2229 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2230 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2231 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2232 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2233 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2234 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2235 }
2236 }
2237
2238 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2239 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2240 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2241 return false;
2242 }
2243
2244 return true;
2245}
2246
Vladimir Markof4da6752014-08-01 19:04:18 +01002247bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2248 static const uint8_t kPadding[] = {
2249 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2250 };
2251 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002252 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002253 return false;
2254 }
2255 size_code_alignment_ += aligned_code_delta;
2256 return true;
2257}
2258
Vladimir Marko944da602016-02-19 12:27:55 +00002259void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2260 DCHECK(dex_files_ != nullptr);
2261 DCHECK(relative_patcher_ != nullptr);
2262 DCHECK_NE(oat_data_offset_, 0u);
2263 if (image_writer_ != nullptr && !dex_files_->empty()) {
2264 // The oat data begin may not be initialized yet but the oat file offset is ready.
2265 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2266 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2267 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002268 }
2269}
2270
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002271OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2272 DexFileSource source,
2273 CreateTypeLookupTable create_type_lookup_table)
2274 : source_(source),
2275 create_type_lookup_table_(create_type_lookup_table),
2276 dex_file_size_(0),
2277 offset_(0),
2278 dex_file_location_size_(strlen(dex_file_location)),
2279 dex_file_location_data_(dex_file_location),
2280 dex_file_location_checksum_(0u),
2281 dex_file_offset_(0u),
2282 class_offsets_offset_(0u),
2283 lookup_table_offset_(0u),
2284 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002285}
2286
2287size_t OatWriter::OatDexFile::SizeOf() const {
2288 return sizeof(dex_file_location_size_)
2289 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002290 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002291 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002292 + sizeof(class_offsets_offset_)
2293 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002294}
2295
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002296void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2297 DCHECK_EQ(lookup_table_offset_, 0u);
2298 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2299 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2300 if (table_size != 0u) {
2301 // Type tables are required to be 4 byte aligned.
2302 size_t original_offset = oat_writer->size_;
2303 size_t offset = RoundUp(original_offset, 4);
2304 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2305 lookup_table_offset_ = offset;
2306 oat_writer->size_ = offset + table_size;
2307 oat_writer->size_oat_lookup_table_ += table_size;
2308 }
2309 }
2310}
2311
2312void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2313 DCHECK_EQ(class_offsets_offset_, 0u);
2314 if (!class_offsets_.empty()) {
2315 // Class offsets are required to be 4 byte aligned.
2316 size_t original_offset = oat_writer->size_;
2317 size_t offset = RoundUp(original_offset, 4);
2318 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2319 class_offsets_offset_ = offset;
2320 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2321 }
2322}
2323
2324bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2325 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002326 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002327
Vladimir Markoe079e212016-05-25 12:49:49 +01002328 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002329 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002330 return false;
2331 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002332 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002333
Vladimir Markoe079e212016-05-25 12:49:49 +01002334 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002335 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002336 return false;
2337 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002338 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002339
Vladimir Markoe079e212016-05-25 12:49:49 +01002340 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002341 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002342 return false;
2343 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002344 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345
Vladimir Markoe079e212016-05-25 12:49:49 +01002346 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002347 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002348 return false;
2349 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002350 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002351
Vladimir Markoe079e212016-05-25 12:49:49 +01002352 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002353 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2354 return false;
2355 }
2356 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2357
Vladimir Markoe079e212016-05-25 12:49:49 +01002358 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002359 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2360 return false;
2361 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002362 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002363
2364 return true;
2365}
2366
2367bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002368 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002369 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2370 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002371 return false;
2372 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002373 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002374 return true;
2375}
2376
Brian Carlstromba150c32013-08-27 17:31:03 -07002377OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002378 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002379 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002380 mirror::Class::Status status)
2381 : compiled_methods_(compiled_methods) {
2382 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002383 CHECK_LE(num_non_null_compiled_methods, num_methods);
2384
Brian Carlstrom265091e2013-01-30 14:08:26 -08002385 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002386 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2387
2388 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2389 // apply when there are 0 methods, we just arbitrarily say that 0
2390 // methods means kOatClassNoneCompiled and that we won't use
2391 // kOatClassAllCompiled unless there is at least one compiled
2392 // method. This means in an interpretter only system, we can assert
2393 // that all classes are kOatClassNoneCompiled.
2394 if (num_non_null_compiled_methods == 0) {
2395 type_ = kOatClassNoneCompiled;
2396 } else if (num_non_null_compiled_methods == num_methods) {
2397 type_ = kOatClassAllCompiled;
2398 } else {
2399 type_ = kOatClassSomeCompiled;
2400 }
2401
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002402 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002403 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002404 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002405
2406 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2407 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002408 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002409 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2410 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2411 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2412 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002413 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002414 method_bitmap_size_ = 0;
2415 }
2416
2417 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002418 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002419 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002420 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2421 } else {
2422 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2423 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2424 if (type_ == kOatClassSomeCompiled) {
2425 method_bitmap_->SetBit(i);
2426 }
2427 }
2428 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002429}
2430
Brian Carlstrom265091e2013-01-30 14:08:26 -08002431size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2432 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002433 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2434 if (method_offset == 0) {
2435 return 0;
2436 }
2437 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002438}
2439
2440size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2441 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002442 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002443}
2444
2445size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002446 return sizeof(status_)
2447 + sizeof(type_)
2448 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2449 + method_bitmap_size_
2450 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002451}
2452
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002453bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002454 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002455 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002456 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002457 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002458 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002459 return false;
2460 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002461 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002462
Vladimir Markoe079e212016-05-25 12:49:49 +01002463 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002464 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002465 return false;
2466 }
2467 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002468
Brian Carlstromba150c32013-08-27 17:31:03 -07002469 if (method_bitmap_size_ != 0) {
2470 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002471 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002472 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002473 return false;
2474 }
2475 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002476
Vladimir Markoe079e212016-05-25 12:49:49 +01002477 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002478 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002479 return false;
2480 }
2481 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2482 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002483
Vladimir Markoe079e212016-05-25 12:49:49 +01002484 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002485 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002486 return false;
2487 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002488 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002489 return true;
2490}
2491
Brian Carlstrome24fa612011-09-29 00:53:55 -07002492} // namespace art