blob: bde00cf886cdab618d41155265f5c967f407b7c5 [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"
David Brazdil7b49e6c2016-09-01 11:06:18 +010042#include "linker/buffered_output_stream.h"
43#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000044#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000045#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/array.h"
47#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010048#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070049#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010050#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070051#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070052#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070053#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030054#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010055#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010056#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070057#include "verifier/method_verifier.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010058#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000059#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070060
61namespace art {
62
Vladimir Marko9bdf1082016-01-21 12:15:52 +000063namespace { // anonymous namespace
64
65typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
66
67const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
68 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
69}
70
Vladimir Markoe079e212016-05-25 12:49:49 +010071class ChecksumUpdatingOutputStream : public OutputStream {
72 public:
73 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
74 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
75
76 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
77 oat_header_->UpdateChecksum(buffer, byte_count);
78 return out_->WriteFully(buffer, byte_count);
79 }
80
81 off_t Seek(off_t offset, Whence whence) OVERRIDE {
82 return out_->Seek(offset, whence);
83 }
84
85 bool Flush() OVERRIDE {
86 return out_->Flush();
87 }
88
89 private:
90 OutputStream* const out_;
91 OatHeader* const oat_header_;
92};
93
Vladimir Marko0c737df2016-08-01 16:33:16 +010094inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
95 // We want to align the code rather than the preheader.
96 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
97 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
98 return aligned_code_offset - unaligned_code_offset;
99}
100
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000101} // anonymous namespace
102
103// Defines the location of the raw dex file to write.
104class OatWriter::DexFileSource {
105 public:
106 explicit DexFileSource(ZipEntry* zip_entry)
107 : type_(kZipEntry), source_(zip_entry) {
108 DCHECK(source_ != nullptr);
109 }
110
111 explicit DexFileSource(File* raw_file)
112 : type_(kRawFile), source_(raw_file) {
113 DCHECK(source_ != nullptr);
114 }
115
116 explicit DexFileSource(const uint8_t* dex_file)
117 : type_(kRawData), source_(dex_file) {
118 DCHECK(source_ != nullptr);
119 }
120
121 bool IsZipEntry() const { return type_ == kZipEntry; }
122 bool IsRawFile() const { return type_ == kRawFile; }
123 bool IsRawData() const { return type_ == kRawData; }
124
125 ZipEntry* GetZipEntry() const {
126 DCHECK(IsZipEntry());
127 DCHECK(source_ != nullptr);
128 return static_cast<ZipEntry*>(const_cast<void*>(source_));
129 }
130
131 File* GetRawFile() const {
132 DCHECK(IsRawFile());
133 DCHECK(source_ != nullptr);
134 return static_cast<File*>(const_cast<void*>(source_));
135 }
136
137 const uint8_t* GetRawData() const {
138 DCHECK(IsRawData());
139 DCHECK(source_ != nullptr);
140 return static_cast<const uint8_t*>(source_);
141 }
142
143 void Clear() {
144 type_ = kNone;
145 source_ = nullptr;
146 }
147
148 private:
149 enum Type {
150 kNone,
151 kZipEntry,
152 kRawFile,
153 kRawData,
154 };
155
156 Type type_;
157 const void* source_;
158};
159
Vladimir Marko49b0f452015-12-10 13:49:19 +0000160class OatWriter::OatClass {
161 public:
162 OatClass(size_t offset,
163 const dchecked_vector<CompiledMethod*>& compiled_methods,
164 uint32_t num_non_null_compiled_methods,
165 mirror::Class::Status status);
166 OatClass(OatClass&& src) = default;
167 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
168 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
169 size_t SizeOf() const;
170 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
171
172 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
173 return compiled_methods_[class_def_method_index];
174 }
175
176 // Offset of start of OatClass from beginning of OatHeader. It is
177 // used to validate file position when writing.
178 size_t offset_;
179
180 // CompiledMethods for each class_def_method_index, or null if no method is available.
181 dchecked_vector<CompiledMethod*> compiled_methods_;
182
183 // Offset from OatClass::offset_ to the OatMethodOffsets for the
184 // class_def_method_index. If 0, it means the corresponding
185 // CompiledMethod entry in OatClass::compiled_methods_ should be
186 // null and that the OatClass::type_ should be kOatClassBitmap.
187 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
188
189 // Data to write.
190
191 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
192 int16_t status_;
193
194 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
195 uint16_t type_;
196
197 uint32_t method_bitmap_size_;
198
199 // bit vector indexed by ClassDef method index. When
200 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
201 // method has an OatMethodOffsets in methods_offsets_, otherwise
202 // the entry was ommited to save space. If OatClassType::type_ is
203 // not is kOatClassBitmap, the bitmap will be null.
204 std::unique_ptr<BitVector> method_bitmap_;
205
206 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
207 // present in the OatClass. Note that some may be missing if
208 // OatClass::compiled_methods_ contains null values (and
209 // oat_method_offsets_offsets_from_oat_class_ should contain 0
210 // values in this case).
211 dchecked_vector<OatMethodOffsets> method_offsets_;
212 dchecked_vector<OatQuickMethodHeader> method_headers_;
213
214 private:
215 size_t GetMethodOffsetsRawSize() const {
216 return method_offsets_.size() * sizeof(method_offsets_[0]);
217 }
218
219 DISALLOW_COPY_AND_ASSIGN(OatClass);
220};
221
222class OatWriter::OatDexFile {
223 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000224 OatDexFile(const char* dex_file_location,
225 DexFileSource source,
226 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000227 OatDexFile(OatDexFile&& src) = default;
228
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000229 const char* GetLocation() const {
230 return dex_file_location_data_;
231 }
232
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000233 void ReserveClassOffsets(OatWriter* oat_writer);
234
Vladimir Marko49b0f452015-12-10 13:49:19 +0000235 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000236 bool Write(OatWriter* oat_writer, OutputStream* out) const;
237 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
238
239 // The source of the dex file.
240 DexFileSource source_;
241
242 // Whether to create the type lookup table.
243 CreateTypeLookupTable create_type_lookup_table_;
244
245 // Dex file size. Initialized when writing the dex file.
246 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000247
248 // Offset of start of OatDexFile from beginning of OatHeader. It is
249 // used to validate file position when writing.
250 size_t offset_;
251
252 // Data to write.
253 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000254 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000255 uint32_t dex_file_location_checksum_;
256 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000257 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000258 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000259
260 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000261 dchecked_vector<uint32_t> class_offsets_;
262
263 private:
264 size_t GetClassOffsetsRawSize() const {
265 return class_offsets_.size() * sizeof(class_offsets_[0]);
266 }
267
268 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
269};
270
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100271#define DCHECK_OFFSET() \
272 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
273 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
274
275#define DCHECK_OFFSET_() \
276 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
277 << "file_offset=" << file_offset << " offset_=" << offset_
278
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000279OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
280 : write_state_(WriteState::kAddingDexFileSources),
281 timings_(timings),
282 raw_dex_files_(),
283 zip_archives_(),
284 zipped_dex_files_(),
285 zipped_dex_file_locations_(),
286 compiler_driver_(nullptr),
287 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800288 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000289 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100290 vdex_size_(0u),
291 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100292 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100293 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100294 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000295 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000296 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000297 bss_roots_offset_(0u),
298 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100299 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700300 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100301 size_vdex_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700302 size_dex_file_alignment_(0),
303 size_executable_offset_alignment_(0),
304 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700305 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700306 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100307 size_verifier_deps_(0),
308 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100309 size_quickening_info_(0),
310 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700311 size_interpreter_to_interpreter_bridge_(0),
312 size_interpreter_to_compiled_code_bridge_(0),
313 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800314 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700315 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700316 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700317 size_quick_to_interpreter_bridge_(0),
318 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100319 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700320 size_code_(0),
321 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100322 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100323 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700324 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700325 size_oat_dex_file_location_size_(0),
326 size_oat_dex_file_location_data_(0),
327 size_oat_dex_file_location_checksum_(0),
328 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000329 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000330 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000331 size_oat_lookup_table_alignment_(0),
332 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000333 size_oat_class_offsets_alignment_(0),
334 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700335 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700336 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700337 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100338 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000339 relative_patcher_(nullptr),
340 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000341}
342
343bool OatWriter::AddDexFileSource(const char* filename,
344 const char* location,
345 CreateTypeLookupTable create_type_lookup_table) {
346 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
347 uint32_t magic;
348 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700349 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
350 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000351 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
352 return false;
353 } else if (IsDexMagic(magic)) {
354 // The file is open for reading, not writing, so it's OK to let the File destructor
355 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700356 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000357 oat_dex_files_.emplace_back(location,
358 DexFileSource(raw_dex_files_.back().get()),
359 create_type_lookup_table);
360 } else if (IsZipMagic(magic)) {
361 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
362 return false;
363 }
364 } else {
365 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
366 return false;
367 }
368 return true;
369}
370
371// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700372bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000373 const char* location,
374 CreateTypeLookupTable create_type_lookup_table) {
375 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
376 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700377 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000378 ZipArchive* zip_archive = zip_archives_.back().get();
379 if (zip_archive == nullptr) {
380 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
381 << error_msg;
382 return false;
383 }
384 for (size_t i = 0; ; ++i) {
385 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
386 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
387 if (entry == nullptr) {
388 break;
389 }
390 zipped_dex_files_.push_back(std::move(entry));
391 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
392 const char* full_location = zipped_dex_file_locations_.back().c_str();
393 oat_dex_files_.emplace_back(full_location,
394 DexFileSource(zipped_dex_files_.back().get()),
395 create_type_lookup_table);
396 }
397 if (zipped_dex_file_locations_.empty()) {
398 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
399 return false;
400 }
401 return true;
402}
403
404// Add dex file source from raw memory.
405bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
406 const char* location,
407 uint32_t location_checksum,
408 CreateTypeLookupTable create_type_lookup_table) {
409 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
410 if (data.size() < sizeof(DexFile::Header)) {
411 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
412 << data.size() << " File: " << location;
413 return false;
414 }
415 if (!ValidateDexFileHeader(data.data(), location)) {
416 return false;
417 }
418 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
419 if (data.size() < header->file_size_) {
420 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
421 << " file size from header: " << header->file_size_ << " File: " << location;
422 return false;
423 }
424
425 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
426 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
427 return true;
428}
429
430dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
431 dchecked_vector<const char*> locations;
432 locations.reserve(oat_dex_files_.size());
433 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
434 locations.push_back(oat_dex_file.GetLocation());
435 }
436 return locations;
437}
438
439bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100440 File* vdex_file,
441 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000442 InstructionSet instruction_set,
443 const InstructionSetFeatures* instruction_set_features,
444 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800445 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000446 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
447 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
448 CHECK(write_state_ == WriteState::kAddingDexFileSources);
449
David Brazdil7b49e6c2016-09-01 11:06:18 +0100450 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
451 if (!RecordOatDataOffset(oat_rodata)) {
452 return false;
453 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000454
455 std::unique_ptr<MemMap> dex_files_map;
456 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100457
458 // Initialize VDEX and OAT headers.
459 if (kIsVdexEnabled) {
460 size_vdex_header_ = sizeof(VdexFile::Header);
461 vdex_size_ = size_vdex_header_;
462 }
463 size_t oat_data_offset = InitOatHeader(instruction_set,
464 instruction_set_features,
465 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
466 key_value_store);
467 oat_size_ = InitOatDexFiles(oat_data_offset);
468
469 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
470
471 if (kIsVdexEnabled) {
472 std::unique_ptr<BufferedOutputStream> vdex_out(
473 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
474
475 // Write DEX files into VDEX, mmap and open them.
476 if (!WriteDexFiles(vdex_out.get(), vdex_file) ||
477 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
478 return false;
479 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100480 } else {
481 // Write DEX files into OAT, mmap and open them.
482 if (!WriteDexFiles(oat_rodata, vdex_file) ||
483 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
484 return false;
485 }
486
487 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
488 // difficult because we're not using the OutputStream directly.
489 if (!oat_dex_files_.empty()) {
490 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
491 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
492 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000494
David Brazdil7b49e6c2016-09-01 11:06:18 +0100495 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000496 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
497 return false;
498 }
499
David Brazdil7b49e6c2016-09-01 11:06:18 +0100500 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000501 for (OatDexFile& oat_dex_file : oat_dex_files_) {
502 oat_dex_file.ReserveClassOffsets(this);
503 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100504
David Brazdil7b49e6c2016-09-01 11:06:18 +0100505 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000506 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
507 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000508 }
509
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000510 *opened_dex_files_map = std::move(dex_files_map);
511 *opened_dex_files = std::move(dex_files);
512 write_state_ = WriteState::kPrepareLayout;
513 return true;
514}
515
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100516void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000517 CHECK(write_state_ == WriteState::kPrepareLayout);
518
Vladimir Marko944da602016-02-19 12:27:55 +0000519 relative_patcher_ = relative_patcher;
520 SetMultiOatRelativePatcherAdjustment();
521
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000522 if (compiling_boot_image_) {
523 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800524 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100525 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000526 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100527
David Brazdil7b49e6c2016-09-01 11:06:18 +0100528 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800529 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800531 offset = InitOatClasses(offset);
532 }
533 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000534 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100535 offset = InitOatMaps(offset);
536 }
537 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000538 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800539 offset = InitOatCode(offset);
540 }
541 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000542 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800543 offset = InitOatCodeDexFiles(offset);
544 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100545 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700546
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800547 if (!HasBootImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000548 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
549 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100550 }
551
Brian Carlstrome24fa612011-09-29 00:53:55 -0700552 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800553 if (compiling_boot_image_) {
554 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000555 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800556 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557
558 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700559}
560
Ian Rogers0571d352011-11-03 19:51:38 -0700561OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700562}
563
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100564class OatWriter::DexMethodVisitor {
565 public:
566 DexMethodVisitor(OatWriter* writer, size_t offset)
567 : writer_(writer),
568 offset_(offset),
569 dex_file_(nullptr),
570 class_def_index_(DexFile::kDexNoIndex) {
571 }
572
573 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
574 DCHECK(dex_file_ == nullptr);
575 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
576 dex_file_ = dex_file;
577 class_def_index_ = class_def_index;
578 return true;
579 }
580
581 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
582
583 virtual bool EndClass() {
584 if (kIsDebugBuild) {
585 dex_file_ = nullptr;
586 class_def_index_ = DexFile::kDexNoIndex;
587 }
588 return true;
589 }
590
591 size_t GetOffset() const {
592 return offset_;
593 }
594
595 protected:
596 virtual ~DexMethodVisitor() { }
597
598 OatWriter* const writer_;
599
600 // The offset is usually advanced for each visited method by the derived class.
601 size_t offset_;
602
603 // The dex file and class def index are set in StartClass().
604 const DexFile* dex_file_;
605 size_t class_def_index_;
606};
607
608class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
609 public:
610 OatDexMethodVisitor(OatWriter* writer, size_t offset)
611 : DexMethodVisitor(writer, offset),
612 oat_class_index_(0u),
613 method_offsets_index_(0u) {
614 }
615
616 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
617 DexMethodVisitor::StartClass(dex_file, class_def_index);
618 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
619 method_offsets_index_ = 0u;
620 return true;
621 }
622
623 bool EndClass() {
624 ++oat_class_index_;
625 return DexMethodVisitor::EndClass();
626 }
627
628 protected:
629 size_t oat_class_index_;
630 size_t method_offsets_index_;
631};
632
633class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
634 public:
635 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
636 : DexMethodVisitor(writer, offset),
637 compiled_methods_(),
638 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000639 size_t num_classes = 0u;
640 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
641 num_classes += oat_dex_file.class_offsets_.size();
642 }
643 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100644 compiled_methods_.reserve(256u);
645 }
646
647 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
648 DexMethodVisitor::StartClass(dex_file, class_def_index);
649 compiled_methods_.clear();
650 num_non_null_compiled_methods_ = 0u;
651 return true;
652 }
653
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300654 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
655 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100656 // Fill in the compiled_methods_ array for methods that have a
657 // CompiledMethod. We track the number of non-null entries in
658 // num_non_null_compiled_methods_ since we only want to allocate
659 // OatMethodOffsets for the compiled methods.
660 uint32_t method_idx = it.GetMemberIndex();
661 CompiledMethod* compiled_method =
662 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
663 compiled_methods_.push_back(compiled_method);
664 if (compiled_method != nullptr) {
665 ++num_non_null_compiled_methods_;
666 }
667 return true;
668 }
669
670 bool EndClass() {
671 ClassReference class_ref(dex_file_, class_def_index_);
672 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
673 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700674 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100675 status = compiled_class->GetStatus();
676 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
677 status = mirror::Class::kStatusError;
678 } else {
679 status = mirror::Class::kStatusNotReady;
680 }
681
Vladimir Marko49b0f452015-12-10 13:49:19 +0000682 writer_->oat_classes_.emplace_back(offset_,
683 compiled_methods_,
684 num_non_null_compiled_methods_,
685 status);
686 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687 return DexMethodVisitor::EndClass();
688 }
689
690 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000691 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100692 size_t num_non_null_compiled_methods_;
693};
694
695class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
696 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100697 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100698 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100699 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
700 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100701 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100702 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
703 }
704
705 bool EndClass() {
706 OatDexMethodVisitor::EndClass();
707 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100708 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100709 }
710 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100711 }
712
713 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700714 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000715 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100716 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
717
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100718 if (it.GetMethodCodeItem() != nullptr) {
719 current_quickening_info_offset_ += sizeof(uint32_t);
720 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100721 if (compiled_method != nullptr) {
722 // Derived from CompiledMethod.
723 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100724
Vladimir Marko35831e82015-09-11 11:59:18 +0100725 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
726 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800727 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800728
David Srbecky009e2a62015-04-15 02:46:30 +0100729 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100730 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800731 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000732 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000733 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
734 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800735 // Duplicate methods, we want the same code for both of them so that the oat writer puts
736 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800737 } else {
738 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100739 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800740 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000741 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100742 quick_code_offset = dedupe_map_.GetOrCreate(
743 compiled_method,
744 [this, &deduped, compiled_method, &it, thumb_offset]() {
745 deduped = false;
746 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
747 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800748 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100749
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100750 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000751 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100752 // TODO: Should this be a hard failure?
753 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700754 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000755 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
756 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100757 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000758 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100759 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800760 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100761
Elliott Hughes956af0f2014-12-11 14:34:28 -0800762 // Update quick method header.
763 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
764 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800765 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Elliott Hughes956af0f2014-12-11 14:34:28 -0800766 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
767 // to 0-offset and we need to adjust it by code_offset.
768 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100769 if (!compiled_method->GetQuickCode().empty()) {
770 // If the code is compiled, we write the offset of the stack map relative
771 // to the code,
772 if (vmap_table_offset != 0u) {
773 vmap_table_offset += code_offset;
774 DCHECK_LT(vmap_table_offset, code_offset);
775 }
776 } else {
777 if (kIsVdexEnabled) {
778 // We write the offset in the .vdex file.
779 DCHECK_EQ(vmap_table_offset, 0u);
780 vmap_table_offset = current_quickening_info_offset_;
781 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
782 current_quickening_info_offset_ += map.size() * sizeof(map.front());
783 } else {
784 // We write the offset of the quickening info relative to the code.
785 vmap_table_offset += code_offset;
786 DCHECK_LT(vmap_table_offset, code_offset);
787 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800788 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800789 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
790 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
791 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100792 *method_header = OatQuickMethodHeader(vmap_table_offset,
793 frame_size_in_bytes,
794 core_spill_mask,
795 fp_spill_mask,
796 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100797
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000798 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800799 // Update offsets. (Checksum is updated when writing.)
800 offset_ += sizeof(*method_header); // Method header is prepended before code.
801 offset_ += code_size;
802 // Record absolute patch locations.
803 if (!compiled_method->GetPatches().empty()) {
804 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
805 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000806 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100807 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100808 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000809 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
810 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
811 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
812 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100813 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100814 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800815 }
Alex Light78382fa2014-06-06 15:45:32 -0700816
David Srbecky91cc06c2016-03-07 16:13:58 +0000817 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000818 // Exclude quickened dex methods (code_size == 0) since they have no native code.
819 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
820 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800821 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000822 debug::MethodDebugInfo info = debug::MethodDebugInfo();
823 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000824 info.dex_file = dex_file_;
825 info.class_def_index = class_def_index_;
826 info.dex_method_index = it.GetMemberIndex();
827 info.access_flags = it.GetMethodAccessFlags();
828 info.code_item = it.GetMethodCodeItem();
829 info.isa = compiled_method->GetInstructionSet();
830 info.deduped = deduped;
831 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
832 info.is_optimized = method_header->IsOptimized();
833 info.is_code_address_text_relative = true;
834 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
835 info.code_size = code_size;
836 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
837 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
838 info.cfi = compiled_method->GetCFIInfo();
839 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100840 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100842 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
843 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
844 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100845 ++method_offsets_index_;
846 }
847
848 return true;
849 }
850
851 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000852 struct CodeOffsetsKeyComparator {
853 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100854 // Code is deduplicated by CompilerDriver, compare only data pointers.
855 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
856 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000857 }
858 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100859 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
860 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000861 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100862 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
863 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000864 }
865 return false;
866 }
867 };
868
David Srbecky009e2a62015-04-15 02:46:30 +0100869 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
870 const ClassDataItemIterator& it,
871 uint32_t thumb_offset) {
872 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100873 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100874 offset_ += CodeAlignmentSize(offset_, *compiled_method);
875 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100876 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
877 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
878 }
879
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100880 // Deduplication is already done on a pointer basis by the compiler driver,
881 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100882 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100883
David Srbecky009e2a62015-04-15 02:46:30 +0100884 // Cache of compiler's --debuggable option.
885 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100886
887 // Offset in the vdex file for the quickening info.
888 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100889};
890
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100891class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
892 public:
893 InitMapMethodVisitor(OatWriter* writer, size_t offset)
894 : OatDexMethodVisitor(writer, offset) {
895 }
896
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700897 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700898 REQUIRES_SHARED(Locks::mutator_lock_) {
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
902 if (compiled_method != nullptr) {
903 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100904 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
905 // be in the vdex file.
906 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
907 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100908
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100909 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
910 uint32_t map_size = map.size() * sizeof(map[0]);
911 if (map_size != 0u) {
912 size_t offset = dedupe_map_.GetOrCreate(
913 map.data(),
914 [this, map_size]() {
915 uint32_t new_offset = offset_;
916 offset_ += map_size;
917 return new_offset;
918 });
919 // Code offset is not initialized yet, so set the map offset to 0u-offset.
920 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
921 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
922 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923 }
924 ++method_offsets_index_;
925 }
926
927 return true;
928 }
929
930 private:
931 // Deduplication is already done on a pointer basis by the compiler driver,
932 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100933 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100934};
935
936class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
937 public:
938 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800939 : OatDexMethodVisitor(writer, offset),
940 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941 }
942
943 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700944 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800945 const DexFile::TypeId& type_id =
946 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
947 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
948 // Skip methods that are not in the image.
949 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
950 return true;
951 }
952
Vladimir Marko49b0f452015-12-10 13:49:19 +0000953 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100954 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
955
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800956 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100957 if (compiled_method != nullptr) {
958 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
959 offsets = oat_class->method_offsets_[method_offsets_index_];
960 ++method_offsets_index_;
961 }
962
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100964 // Unchecked as we hold mutator_lock_ on entry.
965 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800966 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700967 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
968 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800969 ArtMethod* method;
970 if (writer_->HasBootImage()) {
971 const InvokeType invoke_type = it.GetMethodInvokeType(
972 dex_file_->GetClassDef(class_def_index_));
973 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
974 *dex_file_,
975 it.GetMemberIndex(),
976 dex_cache,
977 ScopedNullHandle<mirror::ClassLoader>(),
978 nullptr,
979 invoke_type);
980 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700981 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -0700982 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800983 soa.Self()->AssertPendingException();
984 mirror::Throwable* exc = soa.Self()->GetException();
985 std::string dump = exc->Dump();
986 LOG(FATAL) << dump;
987 UNREACHABLE();
988 }
989 } else {
990 // Should already have been resolved by the compiler, just peek into the dex cache.
991 // It may not be resolved if the class failed to verify, in this case, don't set the
992 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
993 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700994 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800995 if (method != nullptr &&
996 compiled_method != nullptr &&
997 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100998 method->SetEntryPointFromQuickCompiledCodePtrSize(
999 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1000 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001001
1002 return true;
1003 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001004
1005 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001006 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001007};
1008
1009class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1010 public:
1011 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001012 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001013 : OatDexMethodVisitor(writer, relative_offset),
1014 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001015 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001016 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001017 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001018 class_linker_(Runtime::Current()->GetClassLinker()),
1019 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001020 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001021 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001022 // If we're creating the image, the address space must be ready so that we can apply patches.
1023 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001024 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001025 }
1026
Vladimir Markof4da6752014-08-01 19:04:18 +01001027 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001028 }
1029
1030 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001031 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001032 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1033 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001034 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001035 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001036 }
1037 return true;
1038 }
1039
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001040 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001041 bool result = OatDexMethodVisitor::EndClass();
1042 if (oat_class_index_ == writer_->oat_classes_.size()) {
1043 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001044 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001045 if (UNLIKELY(offset_ == 0u)) {
1046 PLOG(ERROR) << "Failed to write final relative call thunks";
1047 result = false;
1048 }
1049 }
1050 return result;
1051 }
1052
1053 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001054 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001055 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001056 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1057
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001058 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001059 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001060 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001061 size_t file_offset = file_offset_;
1062 OutputStream* out = out_;
1063
Vladimir Marko35831e82015-09-11 11:59:18 +01001064 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1065 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001066
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001067 // Deduplicate code arrays.
1068 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1069 if (method_offsets.code_offset_ > offset_) {
1070 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1071 if (offset_ == 0u) {
1072 ReportWriteFailure("relative call thunk", it);
1073 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001074 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001075 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1076 if (alignment_size != 0) {
1077 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001078 ReportWriteFailure("code alignment padding", it);
1079 return false;
1080 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001081 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001082 DCHECK_OFFSET_();
1083 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001084 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001085 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1086 DCHECK_EQ(method_offsets.code_offset_,
1087 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001088 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001089 const OatQuickMethodHeader& method_header =
1090 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001091 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001092 ReportWriteFailure("method header", it);
1093 return false;
1094 }
1095 writer_->size_method_header_ += sizeof(method_header);
1096 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001097 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001098
1099 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001100 patched_code_.assign(quick_code.begin(), quick_code.end());
1101 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001102 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001103 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001104 switch (patch.GetType()) {
1105 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001106 // NOTE: Relative calls across oat files are not supported.
1107 uint32_t target_offset = GetTargetOffset(patch);
1108 writer_->relative_patcher_->PatchCall(&patched_code_,
1109 literal_offset,
1110 offset_ + literal_offset,
1111 target_offset);
1112 break;
1113 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001114 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001115 uint32_t target_offset = GetDexCacheOffset(patch);
1116 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1117 patch,
1118 offset_ + literal_offset,
1119 target_offset);
1120 break;
1121 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001122 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001123 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1124 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1125 patch,
1126 offset_ + literal_offset,
1127 target_offset);
1128 break;
1129 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001130 case LinkerPatch::Type::kStringBssEntry: {
1131 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1132 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1133 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1134 patch,
1135 offset_ + literal_offset,
1136 target_offset);
1137 break;
1138 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001139 case LinkerPatch::Type::kTypeRelative: {
1140 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1141 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1142 patch,
1143 offset_ + literal_offset,
1144 target_offset);
1145 break;
1146 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001147 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001148 uint32_t target_offset = GetTargetOffset(patch);
1149 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1150 break;
1151 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001152 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001153 ArtMethod* method = GetTargetMethod(patch);
1154 PatchMethodAddress(&patched_code_, literal_offset, method);
1155 break;
1156 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001157 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001158 mirror::String* string = GetTargetString(patch);
1159 PatchObjectAddress(&patched_code_, literal_offset, string);
1160 break;
1161 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001162 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001163 mirror::Class* type = GetTargetType(patch);
1164 PatchObjectAddress(&patched_code_, literal_offset, type);
1165 break;
1166 }
1167 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001168 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001169 break;
1170 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001171 }
1172 }
1173 }
1174
Vladimir Markoe079e212016-05-25 12:49:49 +01001175 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001176 ReportWriteFailure("method code", it);
1177 return false;
1178 }
1179 writer_->size_code_ += code_size;
1180 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001181 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001182 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001183 ++method_offsets_index_;
1184 }
1185
1186 return true;
1187 }
1188
1189 private:
1190 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001191 const size_t file_offset_;
1192 const ScopedObjectAccess soa_;
1193 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001194 ClassLinker* const class_linker_;
1195 mirror::DexCache* dex_cache_;
1196 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001197
1198 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1199 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001200 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001201 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001202
Mathieu Chartiere401d142015-04-22 13:56:20 -07001203 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001204 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001205 MethodReference ref = patch.TargetMethod();
1206 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001207 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1208 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001209 ArtMethod* method = dex_cache->GetResolvedMethod(
1210 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001211 CHECK(method != nullptr);
1212 return method;
1213 }
1214
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001215 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001216 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1217 // If there's no new compiled code, either we're compiling an app and the target method
1218 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001219 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001220 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001221 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001222 PointerSize size =
1223 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001224 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1225 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001226 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001227 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1228 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1229 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1230 target_offset = PointerToLowMemUInt32(oat_code_offset);
1231 } else {
1232 target_offset = target->IsNative()
1233 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1234 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1235 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001236 }
1237 return target_offset;
1238 }
1239
Vladimir Marko052164a2016-04-27 13:54:18 +01001240 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001241 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001242 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001243 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001244 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1245 }
1246
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001247 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001248 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001249 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1250 CHECK(type != nullptr);
1251 return type;
1252 }
1253
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001254 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001255 ScopedObjectAccessUnchecked soa(Thread::Current());
1256 StackHandleScope<1> hs(soa.Self());
1257 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1258 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1259 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1260 patch.TargetStringIndex(),
1261 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001262 DCHECK(string != nullptr);
1263 DCHECK(writer_->HasBootImage() ||
1264 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1265 return string;
1266 }
1267
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001268 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001269 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001270 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1271 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1272 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1273 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001274 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001275 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001276 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1277 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001278 }
1279 }
1280
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001281 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001282 DCHECK(writer_->HasBootImage());
1283 object = writer_->image_writer_->GetImageAddress(object);
1284 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1285 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1286 // TODO: Clean up offset types. The target offset must be treated as signed.
1287 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1288 }
1289
Vladimir Markof4da6752014-08-01 19:04:18 +01001290 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001291 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001292 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001293 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001294 } else {
1295 // NOTE: We're using linker patches for app->boot references when the image can
1296 // be relocated and therefore we need to emit .oat_patches. We're not using this
1297 // for app->app references, so check that the object is in the image space.
1298 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001299 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001300 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001301 uint32_t address = PointerToLowMemUInt32(object);
1302 DCHECK_LE(offset + 4, code->size());
1303 uint8_t* data = &(*code)[offset];
1304 data[0] = address & 0xffu;
1305 data[1] = (address >> 8) & 0xffu;
1306 data[2] = (address >> 16) & 0xffu;
1307 data[3] = (address >> 24) & 0xffu;
1308 }
1309
Mathieu Chartiere401d142015-04-22 13:56:20 -07001310 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001311 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001312 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001313 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001314 } else if (kIsDebugBuild) {
1315 // NOTE: We're using linker patches for app->boot references when the image can
1316 // be relocated and therefore we need to emit .oat_patches. We're not using this
1317 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001318 std::vector<gc::space::ImageSpace*> image_spaces =
1319 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1320 bool contains_method = false;
1321 for (gc::space::ImageSpace* image_space : image_spaces) {
1322 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1323 contains_method |=
1324 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1325 }
1326 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001327 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001328 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001329 uint32_t address = PointerToLowMemUInt32(method);
1330 DCHECK_LE(offset + 4, code->size());
1331 uint8_t* data = &(*code)[offset];
1332 data[0] = address & 0xffu;
1333 data[1] = (address >> 8) & 0xffu;
1334 data[2] = (address >> 16) & 0xffu;
1335 data[3] = (address >> 24) & 0xffu;
1336 }
1337
Vladimir Markof4da6752014-08-01 19:04:18 +01001338 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001339 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001340 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001341 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001342 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1343 // TODO: Clean up offset types.
1344 // The target_offset must be treated as signed for cross-oat patching.
1345 const void* target = reinterpret_cast<const void*>(
1346 writer_->image_writer_->GetOatDataBegin(oat_index) +
1347 static_cast<int32_t>(target_offset));
1348 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001349 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001350 DCHECK_LE(offset + 4, code->size());
1351 uint8_t* data = &(*code)[offset];
1352 data[0] = address & 0xffu;
1353 data[1] = (address >> 8) & 0xffu;
1354 data[2] = (address >> 16) & 0xffu;
1355 data[3] = (address >> 24) & 0xffu;
1356 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001357};
1358
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001359class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1360 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001361 WriteMapMethodVisitor(OatWriter* writer,
1362 OutputStream* out,
1363 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001364 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001365 : OatDexMethodVisitor(writer, relative_offset),
1366 out_(out),
1367 file_offset_(file_offset) {
1368 }
1369
1370 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001371 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001372 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1373
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001374 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001375 size_t file_offset = file_offset_;
1376 OutputStream* out = out_;
1377
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001378 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1379 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001380 ++method_offsets_index_;
1381
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001382 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1383 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1384 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001385 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001386
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001387 // If vdex is enabled, only emit the map for compiled code. The quickening info
1388 // is emitted in the vdex already.
1389 if (map_offset != 0u &&
1390 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001391 // Transform map_offset to actual oat data offset.
1392 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1393 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001394 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001395
1396 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1397 size_t map_size = map.size() * sizeof(map[0]);
1398 if (map_offset == offset_) {
1399 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001400 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001401 ReportWriteFailure(it);
1402 return false;
1403 }
1404 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001405 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001406 }
1407 DCHECK_OFFSET_();
1408 }
1409
1410 return true;
1411 }
1412
1413 private:
1414 OutputStream* const out_;
1415 size_t const file_offset_;
1416
1417 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001418 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001419 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420 }
1421};
1422
1423// Visit all methods from all classes in all dex files with the specified visitor.
1424bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1425 for (const DexFile* dex_file : *dex_files_) {
1426 const size_t class_def_count = dex_file->NumClassDefs();
1427 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1428 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1429 return false;
1430 }
1431 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001432 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001433 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434 ClassDataItemIterator it(*dex_file, class_data);
1435 while (it.HasNextStaticField()) {
1436 it.Next();
1437 }
1438 while (it.HasNextInstanceField()) {
1439 it.Next();
1440 }
1441 size_t class_def_method_index = 0u;
1442 while (it.HasNextDirectMethod()) {
1443 if (!visitor->VisitMethod(class_def_method_index, it)) {
1444 return false;
1445 }
1446 ++class_def_method_index;
1447 it.Next();
1448 }
1449 while (it.HasNextVirtualMethod()) {
1450 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1451 return false;
1452 }
1453 ++class_def_method_index;
1454 it.Next();
1455 }
1456 }
1457 if (UNLIKELY(!visitor->EndClass())) {
1458 return false;
1459 }
1460 }
1461 }
1462 return true;
1463}
1464
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001465size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1466 const InstructionSetFeatures* instruction_set_features,
1467 uint32_t num_dex_files,
1468 SafeMap<std::string, std::string>* key_value_store) {
1469 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1470 oat_header_.reset(OatHeader::Create(instruction_set,
1471 instruction_set_features,
1472 num_dex_files,
1473 key_value_store));
1474 size_oat_header_ += sizeof(OatHeader);
1475 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001476 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001477}
1478
1479size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001480 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1481 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001482 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001483 oat_dex_file.offset_ = offset;
1484 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001485 }
1486 return offset;
1487}
1488
Brian Carlstrom389efb02012-01-11 12:06:26 -08001489size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001490 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001491 InitOatClassesMethodVisitor visitor(this, offset);
1492 bool success = VisitDexMethods(&visitor);
1493 CHECK(success);
1494 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001495
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001496 // Update oat_dex_files_.
1497 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001498 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1499 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001500 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001501 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001502 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001503 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001504 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001505 CHECK(oat_class_it == oat_classes_.end());
1506
1507 return offset;
1508}
1509
1510size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001511 InitMapMethodVisitor visitor(this, offset);
1512 bool success = VisitDexMethods(&visitor);
1513 DCHECK(success);
1514 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001515
Brian Carlstrome24fa612011-09-29 00:53:55 -07001516 return offset;
1517}
1518
1519size_t OatWriter::InitOatCode(size_t offset) {
1520 // calculate the offsets within OatHeader to executable code
1521 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001522 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001523 // required to be on a new page boundary
1524 offset = RoundUp(offset, kPageSize);
1525 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001526 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001527 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001528 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001529
Ian Rogers848871b2013-08-05 10:56:33 -07001530 #define DO_TRAMPOLINE(field, fn_name) \
1531 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001532 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1533 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001534 (field) = compiler_driver_->Create ## fn_name(); \
1535 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001536
Ian Rogers848871b2013-08-05 10:56:33 -07001537 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001538 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001539 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001540 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1541 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001542
Ian Rogers848871b2013-08-05 10:56:33 -07001543 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001544 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001545 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1546 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1547 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001548 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001549 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001550 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001551 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001552 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001553 return offset;
1554}
1555
1556size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001557 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1558 bool success = VisitDexMethods(&code_visitor);
1559 DCHECK(success);
1560 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001561
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001562 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001563 InitImageMethodVisitor image_visitor(this, offset);
1564 success = VisitDexMethods(&image_visitor);
1565 DCHECK(success);
1566 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001567 }
Logan Chien8b977d32012-02-21 19:14:55 +08001568
Brian Carlstrome24fa612011-09-29 00:53:55 -07001569 return offset;
1570}
1571
Vladimir Markoaad75c62016-10-03 08:46:48 +00001572void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1573 DCHECK(!HasBootImage());
1574
1575 // Allocate space for app dex cache arrays in the .bss section.
1576 bss_start_ = RoundUp(oat_size_, kPageSize);
1577 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1578 bss_size_ = 0u;
1579 for (const DexFile* dex_file : *dex_files_) {
1580 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1581 DexCacheArraysLayout layout(pointer_size, dex_file);
1582 bss_size_ += layout.Size();
1583 }
1584
1585 bss_roots_offset_ = bss_size_;
1586
1587 // Prepare offsets for .bss String entries.
1588 for (auto& entry : bss_string_entries_) {
1589 DCHECK_EQ(entry.second, 0u);
1590 entry.second = bss_start_ + bss_size_;
1591 bss_size_ += sizeof(GcRoot<mirror::String>);
1592 }
1593}
1594
David Srbeckybc90fd02015-04-22 19:40:27 +01001595bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001596 CHECK(write_state_ == WriteState::kWriteRoData);
1597
Vladimir Markoe079e212016-05-25 12:49:49 +01001598 // Wrap out to update checksum with each write.
1599 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1600 out = &checksum_updating_out;
1601
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001602 if (!WriteClassOffsets(out)) {
1603 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001604 return false;
1605 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001606
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001607 if (!WriteClasses(out)) {
1608 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001609 return false;
1610 }
1611
Vladimir Markof4da6752014-08-01 19:04:18 +01001612 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001613 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001614 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001615 return false;
1616 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001617 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001618 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001619 relative_offset = WriteMaps(out, file_offset, relative_offset);
1620 if (relative_offset == 0) {
1621 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1622 return false;
1623 }
1624
David Srbeckybc90fd02015-04-22 19:40:27 +01001625 // Write padding.
1626 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1627 relative_offset += size_executable_offset_alignment_;
1628 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1629 size_t expected_file_offset = file_offset + relative_offset;
1630 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1631 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1632 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1633 return 0;
1634 }
1635 DCHECK_OFFSET();
1636
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001637 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001638 return true;
1639}
1640
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001641class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1642 public:
1643 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1644 : DexMethodVisitor(writer, offset),
1645 out_(out),
1646 written_bytes_(0u) {}
1647
1648 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1649 const ClassDataItemIterator& it) {
1650 if (it.GetMethodCodeItem() == nullptr) {
1651 // No CodeItem. Native or abstract method.
1652 return true;
1653 }
1654
1655 uint32_t method_idx = it.GetMemberIndex();
1656 CompiledMethod* compiled_method =
1657 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1658
1659 uint32_t length = 0;
1660 const uint8_t* data = nullptr;
1661 // VMap only contains quickening info if this method is not compiled.
1662 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1663 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1664 data = map.data();
1665 length = map.size() * sizeof(map.front());
1666 }
1667
1668 if (!out_->WriteFully(&length, sizeof(length)) ||
1669 !out_->WriteFully(data, length)) {
1670 PLOG(ERROR) << "Failed to write quickening info for "
1671 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1672 return false;
1673 }
1674 offset_ += sizeof(length) + length;
1675 written_bytes_ += sizeof(length) + length;
1676 return true;
1677 }
1678
1679 size_t GetNumberOfWrittenBytes() const {
1680 return written_bytes_;
1681 }
1682
1683 private:
1684 OutputStream* const out_;
1685 size_t written_bytes_;
1686};
1687
1688bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1689 if (!kIsVdexEnabled) {
1690 return true;
1691 }
1692
1693 size_t initial_offset = vdex_size_;
1694 size_t start_offset = RoundUp(initial_offset, 4u);
1695
1696 vdex_size_ = start_offset;
1697 vdex_quickening_info_offset_ = vdex_size_;
1698 size_quickening_info_alignment_ = start_offset - initial_offset;
1699
1700 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1701 if (actual_offset != static_cast<off_t>(start_offset)) {
1702 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1703 << " Expected: " << start_offset
1704 << " Output: " << vdex_out->GetLocation();
1705 return false;
1706 }
1707
1708 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1709 if (!VisitDexMethods(&visitor)) {
1710 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1711 return false;
1712 }
1713
1714 if (!vdex_out->Flush()) {
1715 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1716 << " File: " << vdex_out->GetLocation();
1717 return false;
1718 }
1719
1720 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1721 vdex_size_ += size_quickening_info_;
1722 return true;
1723}
1724
David Brazdil5d5a36b2016-09-14 15:34:10 +01001725bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1726 if (!kIsVdexEnabled) {
1727 return true;
1728 }
1729
1730 if (verifier_deps == nullptr) {
1731 // Nothing to write. Record the offset, but no need
1732 // for alignment.
1733 vdex_verifier_deps_offset_ = vdex_size_;
1734 return true;
1735 }
1736
1737 size_t initial_offset = vdex_size_;
1738 size_t start_offset = RoundUp(initial_offset, 4u);
1739
1740 vdex_size_ = start_offset;
1741 vdex_verifier_deps_offset_ = vdex_size_;
1742 size_verifier_deps_alignment_ = start_offset - initial_offset;
1743
1744 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1745 if (actual_offset != static_cast<off_t>(start_offset)) {
1746 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1747 << " Expected: " << start_offset
1748 << " Output: " << vdex_out->GetLocation();
1749 return false;
1750 }
1751
1752 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001753 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001754
1755 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1756 PLOG(ERROR) << "Failed to write verifier deps."
1757 << " File: " << vdex_out->GetLocation();
1758 return false;
1759 }
1760 if (!vdex_out->Flush()) {
1761 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1762 << " File: " << vdex_out->GetLocation();
1763 return false;
1764 }
1765
1766 size_verifier_deps_ = buffer.size();
1767 vdex_size_ += size_verifier_deps_;
1768 return true;
1769}
1770
David Srbeckybc90fd02015-04-22 19:40:27 +01001771bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001772 CHECK(write_state_ == WriteState::kWriteText);
1773
Vladimir Markoe079e212016-05-25 12:49:49 +01001774 // Wrap out to update checksum with each write.
1775 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1776 out = &checksum_updating_out;
1777
Vladimir Marko944da602016-02-19 12:27:55 +00001778 SetMultiOatRelativePatcherAdjustment();
1779
David Srbeckybc90fd02015-04-22 19:40:27 +01001780 const size_t file_offset = oat_data_offset_;
1781 size_t relative_offset = oat_header_->GetExecutableOffset();
1782 DCHECK_OFFSET();
1783
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001784 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001785 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001786 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001787 return false;
1788 }
1789
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001790 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1791 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001792 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001793 return false;
1794 }
1795
Vladimir Markof4da6752014-08-01 19:04:18 +01001796 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001797 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001798 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1799 return false;
1800 }
1801
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001802 if (kIsDebugBuild) {
1803 uint32_t size_total = 0;
1804 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001805 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1806 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001807
David Brazdil7b49e6c2016-09-01 11:06:18 +01001808 DO_STAT(size_vdex_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001809 DO_STAT(size_dex_file_alignment_);
1810 DO_STAT(size_executable_offset_alignment_);
1811 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001812 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001813 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001814 DO_STAT(size_verifier_deps_);
1815 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001816 DO_STAT(size_quickening_info_);
1817 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001818 DO_STAT(size_interpreter_to_interpreter_bridge_);
1819 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1820 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001821 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001822 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001823 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001824 DO_STAT(size_quick_to_interpreter_bridge_);
1825 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001826 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001827 DO_STAT(size_code_);
1828 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001829 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001830 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001831 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001832 DO_STAT(size_oat_dex_file_location_size_);
1833 DO_STAT(size_oat_dex_file_location_data_);
1834 DO_STAT(size_oat_dex_file_location_checksum_);
1835 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001836 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001837 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001838 DO_STAT(size_oat_lookup_table_alignment_);
1839 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001840 DO_STAT(size_oat_class_offsets_alignment_);
1841 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001842 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001843 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001844 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001845 DO_STAT(size_oat_class_method_offsets_);
1846 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001847
David Brazdil7b49e6c2016-09-01 11:06:18 +01001848 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1849
1850 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1851 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001852 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001853
David Brazdil7b49e6c2016-09-01 11:06:18 +01001854 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1855 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001856
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001857 write_state_ = WriteState::kWriteHeader;
1858 return true;
1859}
1860
1861bool OatWriter::WriteHeader(OutputStream* out,
1862 uint32_t image_file_location_oat_checksum,
1863 uintptr_t image_file_location_oat_begin,
1864 int32_t image_patch_delta) {
1865 CHECK(write_state_ == WriteState::kWriteHeader);
1866
1867 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1868 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001869 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001870 CHECK_EQ(image_patch_delta, 0);
1871 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1872 } else {
1873 CHECK_ALIGNED(image_patch_delta, kPageSize);
1874 oat_header_->SetImagePatchDelta(image_patch_delta);
1875 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001876 oat_header_->UpdateChecksumWithHeaderData();
1877
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001878 const size_t file_offset = oat_data_offset_;
1879
1880 off_t current_offset = out->Seek(0, kSeekCurrent);
1881 if (current_offset == static_cast<off_t>(-1)) {
1882 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1883 return false;
1884 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001885 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001886 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1887 return false;
1888 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001889 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001890
1891 // Flush all other data before writing the header.
1892 if (!out->Flush()) {
1893 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1894 return false;
1895 }
1896 // Write the header.
1897 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001898 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001899 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1900 return false;
1901 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001902 // Flush the header data.
1903 if (!out->Flush()) {
1904 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001905 return false;
1906 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001907
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001908 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1909 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1910 return false;
1911 }
1912 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1913
1914 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001915 return true;
1916}
1917
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001918bool OatWriter::WriteClassOffsets(OutputStream* out) {
1919 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1920 if (oat_dex_file.class_offsets_offset_ != 0u) {
1921 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1922 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1923 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1924 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1925 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001926 return false;
1927 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001928 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1929 return false;
1930 }
1931 }
1932 }
1933 return true;
1934}
1935
1936bool OatWriter::WriteClasses(OutputStream* out) {
1937 for (OatClass& oat_class : oat_classes_) {
1938 if (!oat_class.Write(this, out, oat_data_offset_)) {
1939 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1940 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001941 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001942 }
1943 return true;
1944}
1945
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001946size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001947 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001948 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1949 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1950 return 0;
1951 }
1952 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001953 size_vmap_table_ = relative_offset - vmap_tables_offset;
1954
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001955 return relative_offset;
1956}
1957
1958size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001959 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001960 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001961
Ian Rogers848871b2013-08-05 10:56:33 -07001962 #define DO_TRAMPOLINE(field) \
1963 do { \
1964 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1965 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001966 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001967 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001968 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001969 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001970 return false; \
1971 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001972 size_ ## field += (field)->size(); \
1973 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001974 DCHECK_OFFSET(); \
1975 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001976
Ian Rogers848871b2013-08-05 10:56:33 -07001977 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001978 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001979 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001980 DO_TRAMPOLINE(quick_resolution_trampoline_);
1981 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1982 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001983 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001984 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001985}
1986
Ian Rogers3d504072014-03-01 09:16:49 -08001987size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001988 const size_t file_offset,
1989 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001990 #define VISIT(VisitorType) \
1991 do { \
1992 VisitorType visitor(this, out, file_offset, relative_offset); \
1993 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1994 return 0; \
1995 } \
1996 relative_offset = visitor.GetOffset(); \
1997 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001998
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001999 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002000
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002001 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002002
Vladimir Markob163bb72015-03-31 21:49:49 +01002003 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2004 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2005 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2006
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002007 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002008}
2009
Vladimir Marko944da602016-02-19 12:27:55 +00002010bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002011 // Get the elf file offset of the oat file.
2012 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2013 if (raw_file_offset == static_cast<off_t>(-1)) {
2014 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2015 return false;
2016 }
2017 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2018 return true;
2019}
2020
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002021bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2022 // Read the dex file header and perform minimal verification.
2023 uint8_t raw_header[sizeof(DexFile::Header)];
2024 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2025 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2026 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2027 return false;
2028 }
2029 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2030 return false;
2031 }
2032
2033 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2034 oat_dex_file->dex_file_size_ = header->file_size_;
2035 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2036 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2037 return true;
2038}
2039
2040bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2041 if (!DexFile::IsMagicValid(raw_header)) {
2042 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2043 return false;
2044 }
2045 if (!DexFile::IsVersionValid(raw_header)) {
2046 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2047 return false;
2048 }
2049 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2050 if (header->file_size_ < sizeof(DexFile::Header)) {
2051 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2052 << " File: " << location;
2053 return false;
2054 }
2055 return true;
2056}
2057
David Brazdil7b49e6c2016-09-01 11:06:18 +01002058bool OatWriter::WriteDexFiles(OutputStream* out, File* file) {
2059 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002060
David Brazdil7b49e6c2016-09-01 11:06:18 +01002061 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002062
2063 // Write dex files.
2064 for (OatDexFile& oat_dex_file : oat_dex_files_) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002065 if (!WriteDexFile(out, file, &oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002066 return false;
2067 }
2068 }
2069
2070 // Close sources.
2071 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2072 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2073 }
2074 zipped_dex_files_.clear();
2075 zip_archives_.clear();
2076 raw_dex_files_.clear();
2077 return true;
2078}
2079
David Brazdil7b49e6c2016-09-01 11:06:18 +01002080bool OatWriter::WriteDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2081 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002082 return false;
2083 }
2084 if (oat_dex_file->source_.IsZipEntry()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002085 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002086 return false;
2087 }
2088 } else if (oat_dex_file->source_.IsRawFile()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002089 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002090 return false;
2091 }
2092 } else {
2093 DCHECK(oat_dex_file->source_.IsRawData());
David Brazdil7b49e6c2016-09-01 11:06:18 +01002094 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002095 return false;
2096 }
2097 }
2098
2099 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002100 if (kIsVdexEnabled) {
2101 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2102 vdex_size_ += oat_dex_file->dex_file_size_;
2103 } else {
2104 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2105 oat_size_ += oat_dex_file->dex_file_size_;
2106 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002107 size_dex_file_ += oat_dex_file->dex_file_size_;
2108 return true;
2109}
2110
2111bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2112 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002113 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2114 size_t start_offset = RoundUp(initial_offset, 4);
2115 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2116 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002117
2118 // Seek to the start of the dex file and flush any pending operations in the stream.
2119 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002120 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2121 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002122 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002123 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002124 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2125 return false;
2126 }
2127 if (!out->Flush()) {
2128 PLOG(ERROR) << "Failed to flush before writing dex file."
2129 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2130 return false;
2131 }
2132 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002133 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002134 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002135 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002136 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2137 return false;
2138 }
2139
David Brazdil7b49e6c2016-09-01 11:06:18 +01002140 if (kIsVdexEnabled) {
2141 vdex_size_ = start_offset;
2142 } else {
2143 oat_size_ = start_offset;
2144 }
2145 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002146 return true;
2147}
2148
David Brazdil7b49e6c2016-09-01 11:06:18 +01002149bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002150 File* file,
2151 OatDexFile* oat_dex_file,
2152 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002153 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2154 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002155
2156 // Extract the dex file and get the extracted size.
2157 std::string error_msg;
2158 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2159 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2160 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2161 return false;
2162 }
2163 if (file->Flush() != 0) {
2164 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2165 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2166 return false;
2167 }
2168 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2169 if (extracted_end == static_cast<off_t>(-1)) {
2170 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2171 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2172 return false;
2173 }
2174 if (extracted_end < static_cast<off_t>(start_offset)) {
2175 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2176 << " Start: " << start_offset
2177 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2178 return false;
2179 }
2180 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2181 if (extracted_size < sizeof(DexFile::Header)) {
2182 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2183 << extracted_size << " File: " << oat_dex_file->GetLocation();
2184 return false;
2185 }
2186
2187 // Read the dex file header and extract required data to OatDexFile.
2188 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2189 if (actual_offset != static_cast<off_t>(start_offset)) {
2190 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2191 << " Expected: " << start_offset
2192 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2193 return false;
2194 }
2195 if (!ReadDexFileHeader(file, oat_dex_file)) {
2196 return false;
2197 }
2198 if (extracted_size < oat_dex_file->dex_file_size_) {
2199 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2200 << " file size from header: " << oat_dex_file->dex_file_size_
2201 << " File: " << oat_dex_file->GetLocation();
2202 return false;
2203 }
2204
2205 // Override the checksum from header with the CRC from ZIP entry.
2206 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2207
2208 // Seek both file and stream to the end offset.
2209 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2210 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2211 if (actual_offset != static_cast<off_t>(end_offset)) {
2212 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2213 << " Expected: " << end_offset
2214 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2215 return false;
2216 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002217 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002218 if (actual_offset != static_cast<off_t>(end_offset)) {
2219 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2220 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2221 return false;
2222 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002223 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002224 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2225 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2226 return false;
2227 }
2228
2229 // If we extracted more than the size specified in the header, truncate the file.
2230 if (extracted_size > oat_dex_file->dex_file_size_) {
2231 if (file->SetLength(end_offset) != 0) {
2232 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002233 << " File: " << oat_dex_file->GetLocation()
2234 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002235 return false;
2236 }
2237 }
2238
2239 return true;
2240}
2241
David Brazdil7b49e6c2016-09-01 11:06:18 +01002242bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002243 File* file,
2244 OatDexFile* oat_dex_file,
2245 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002246 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2247 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002248
2249 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2250 if (input_offset != static_cast<off_t>(0)) {
2251 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2252 << " Expected: 0"
2253 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2254 return false;
2255 }
2256 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2257 return false;
2258 }
2259
2260 // Copy the input dex file using sendfile().
2261 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2262 PLOG(ERROR) << "Failed to copy dex file to oat file."
2263 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2264 return false;
2265 }
2266 if (file->Flush() != 0) {
2267 PLOG(ERROR) << "Failed to flush dex file."
2268 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2269 return false;
2270 }
2271
2272 // Check file position and seek the stream to the end offset.
2273 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2274 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2275 if (actual_offset != static_cast<off_t>(end_offset)) {
2276 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2277 << " Expected: " << end_offset
2278 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2279 return false;
2280 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002281 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002282 if (actual_offset != static_cast<off_t>(end_offset)) {
2283 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2284 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2285 return false;
2286 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002287 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002288 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2289 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2290 return false;
2291 }
2292
2293 return true;
2294}
2295
David Brazdil7b49e6c2016-09-01 11:06:18 +01002296bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002297 OatDexFile* oat_dex_file,
2298 const uint8_t* dex_file) {
2299 // Note: The raw data has already been checked to contain the header
2300 // and all the data that the header specifies as the file size.
2301 DCHECK(dex_file != nullptr);
2302 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2303 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2304
David Brazdil7b49e6c2016-09-01 11:06:18 +01002305 if (!out->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002306 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002307 << " to " << out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002308 return false;
2309 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002310 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002311 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2312 << " File: " << oat_dex_file->GetLocation();
2313 return false;
2314 }
2315
2316 // Update dex file size and resize class offsets in the OatDexFile.
2317 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2318 oat_dex_file->dex_file_size_ = header->file_size_;
2319 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2320 return true;
2321}
2322
2323bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2324 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2325
David Brazdil181e1cc2016-09-01 16:38:47 +00002326 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2327 if (initial_offset == static_cast<off_t>(-1)) {
2328 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2329 return false;
2330 }
2331
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002332 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2333 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2334 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2335 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2336 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2337 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2338 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2339 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2340 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2341 return false;
2342 }
2343
2344 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2345 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2346
2347 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2348 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2349
2350 // Write OatDexFile.
2351 if (!oat_dex_file->Write(this, rodata)) {
2352 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2353 return false;
2354 }
2355 }
2356
David Brazdil181e1cc2016-09-01 16:38:47 +00002357 // Seek back to the initial position.
2358 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2359 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2360 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2361 return false;
2362 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002363
David Brazdilb92ba622016-09-01 16:00:30 +00002364 return true;
2365}
2366
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367bool OatWriter::OpenDexFiles(
2368 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002369 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002370 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2371 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2372 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2373
2374 if (oat_dex_files_.empty()) {
2375 // Nothing to do.
2376 return true;
2377 }
2378
2379 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002380 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2381
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002382 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002383 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2384 length,
2385 PROT_READ | PROT_WRITE,
2386 MAP_SHARED,
2387 file->Fd(),
2388 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2389 /* low_4gb */ false,
2390 file->GetPath().c_str(),
2391 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002392 if (dex_files_map == nullptr) {
2393 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2394 << " error: " << error_msg;
2395 return false;
2396 }
2397 std::vector<std::unique_ptr<const DexFile>> dex_files;
2398 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2399 // Make sure no one messed with input files while we were copying data.
2400 // At the very least we need consistent file size and number of class definitions.
2401 const uint8_t* raw_dex_file =
2402 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2403 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2404 // Note: ValidateDexFileHeader() already logged an error message.
2405 LOG(ERROR) << "Failed to verify written dex file header!"
2406 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2407 << " ~ " << static_cast<const void*>(raw_dex_file);
2408 return false;
2409 }
2410 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2411 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2412 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2413 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2414 << " Output: " << file->GetPath();
2415 return false;
2416 }
2417 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2418 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2419 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2420 << " Output: " << file->GetPath();
2421 return false;
2422 }
2423
2424 // Now, open the dex file.
2425 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2426 oat_dex_file.dex_file_size_,
2427 oat_dex_file.GetLocation(),
2428 oat_dex_file.dex_file_location_checksum_,
2429 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002430 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002431 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002432 &error_msg));
2433 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002434 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2435 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002436 return false;
2437 }
2438 }
2439
2440 *opened_dex_files_map = std::move(dex_files_map);
2441 *opened_dex_files = std::move(dex_files);
2442 return true;
2443}
2444
2445bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002446 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002447 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2448 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2449
David Brazdil7b49e6c2016-09-01 11:06:18 +01002450 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2451 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2452 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2453 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2454 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2455 return false;
2456 }
2457
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002458 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2459 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2460 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002461 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2462
2463 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2464 oat_dex_file->class_offsets_.empty()) {
2465 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002466 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002467
2468 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2469 if (table_size == 0u) {
2470 continue;
2471 }
2472
2473 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002474 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002475 const DexFile& dex_file = *opened_dex_files[i];
2476 {
2477 std::unique_ptr<TypeLookupTable> type_lookup_table =
2478 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2479 type_lookup_table_oat_dex_files_.push_back(
2480 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2481 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2482 }
2483 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002484
2485 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002486 size_t initial_offset = oat_size_;
2487 size_t rodata_offset = RoundUp(initial_offset, 4);
2488 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002489
2490 if (padding_size != 0u) {
2491 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002492 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002493 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2494 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002495 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002496 return false;
2497 }
2498 }
2499
2500 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002501 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002502 DCHECK_EQ(table_size, table->RawDataLength());
2503
David Brazdil7b49e6c2016-09-01 11:06:18 +01002504 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002505 PLOG(ERROR) << "Failed to write lookup table."
2506 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002507 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002508 return false;
2509 }
2510
2511 oat_dex_file->lookup_table_offset_ = rodata_offset;
2512
David Brazdil7b49e6c2016-09-01 11:06:18 +01002513 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002514 size_oat_lookup_table_ += table_size;
2515 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002516 }
2517
David Brazdil7b49e6c2016-09-01 11:06:18 +01002518 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002519 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002520 << " File: " << oat_rodata->GetLocation();
2521 return false;
2522 }
2523
2524 return true;
2525}
2526
2527bool OatWriter::WriteVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002528 if (!kIsVdexEnabled) {
2529 return true;
2530 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002531 off_t actual_offset = vdex_out->Seek(0, kSeekSet);
2532 if (actual_offset != 0) {
2533 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2534 << " File: " << vdex_out->GetLocation();
2535 return false;
2536 }
2537
David Brazdil5d5a36b2016-09-14 15:34:10 +01002538 DCHECK_NE(vdex_dex_files_offset_, 0u);
2539 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2540
2541 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002542 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2543 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002544
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002545 VdexFile::Header vdex_header(
2546 dex_section_size, verifier_deps_section_size, quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002547 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2548 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002549 return false;
2550 }
2551
David Brazdil5d5a36b2016-09-14 15:34:10 +01002552 if (!vdex_out->Flush()) {
2553 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2554 << " File: " << vdex_out->GetLocation();
2555 return false;
2556 }
2557
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002558 return true;
2559}
2560
Vladimir Markof4da6752014-08-01 19:04:18 +01002561bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2562 static const uint8_t kPadding[] = {
2563 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2564 };
2565 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002566 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002567 return false;
2568 }
2569 size_code_alignment_ += aligned_code_delta;
2570 return true;
2571}
2572
Vladimir Marko944da602016-02-19 12:27:55 +00002573void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2574 DCHECK(dex_files_ != nullptr);
2575 DCHECK(relative_patcher_ != nullptr);
2576 DCHECK_NE(oat_data_offset_, 0u);
2577 if (image_writer_ != nullptr && !dex_files_->empty()) {
2578 // The oat data begin may not be initialized yet but the oat file offset is ready.
2579 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2580 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2581 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002582 }
2583}
2584
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002585OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2586 DexFileSource source,
2587 CreateTypeLookupTable create_type_lookup_table)
2588 : source_(source),
2589 create_type_lookup_table_(create_type_lookup_table),
2590 dex_file_size_(0),
2591 offset_(0),
2592 dex_file_location_size_(strlen(dex_file_location)),
2593 dex_file_location_data_(dex_file_location),
2594 dex_file_location_checksum_(0u),
2595 dex_file_offset_(0u),
2596 class_offsets_offset_(0u),
2597 lookup_table_offset_(0u),
2598 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002599}
2600
2601size_t OatWriter::OatDexFile::SizeOf() const {
2602 return sizeof(dex_file_location_size_)
2603 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002604 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002605 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002606 + sizeof(class_offsets_offset_)
2607 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002608}
2609
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002610void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2611 DCHECK_EQ(class_offsets_offset_, 0u);
2612 if (!class_offsets_.empty()) {
2613 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002614 size_t initial_offset = oat_writer->oat_size_;
2615 size_t offset = RoundUp(initial_offset, 4);
2616 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002617 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002618 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002619 }
2620}
2621
2622bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2623 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002624 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002625
Vladimir Markoe079e212016-05-25 12:49:49 +01002626 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002627 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002628 return false;
2629 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002630 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002631
Vladimir Markoe079e212016-05-25 12:49:49 +01002632 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002633 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002634 return false;
2635 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002636 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002637
Vladimir Markoe079e212016-05-25 12:49:49 +01002638 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002639 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002640 return false;
2641 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002642 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002643
Vladimir Markoe079e212016-05-25 12:49:49 +01002644 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002645 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002646 return false;
2647 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002648 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002649
Vladimir Markoe079e212016-05-25 12:49:49 +01002650 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002651 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2652 return false;
2653 }
2654 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2655
Vladimir Markoe079e212016-05-25 12:49:49 +01002656 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002657 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2658 return false;
2659 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002660 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002661
2662 return true;
2663}
2664
2665bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002666 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002667 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2668 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002669 return false;
2670 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002671 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002672 return true;
2673}
2674
Brian Carlstromba150c32013-08-27 17:31:03 -07002675OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002676 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002677 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002678 mirror::Class::Status status)
2679 : compiled_methods_(compiled_methods) {
2680 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002681 CHECK_LE(num_non_null_compiled_methods, num_methods);
2682
Brian Carlstrom265091e2013-01-30 14:08:26 -08002683 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002684 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2685
2686 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2687 // apply when there are 0 methods, we just arbitrarily say that 0
2688 // methods means kOatClassNoneCompiled and that we won't use
2689 // kOatClassAllCompiled unless there is at least one compiled
2690 // method. This means in an interpretter only system, we can assert
2691 // that all classes are kOatClassNoneCompiled.
2692 if (num_non_null_compiled_methods == 0) {
2693 type_ = kOatClassNoneCompiled;
2694 } else if (num_non_null_compiled_methods == num_methods) {
2695 type_ = kOatClassAllCompiled;
2696 } else {
2697 type_ = kOatClassSomeCompiled;
2698 }
2699
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002700 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002701 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002702 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002703
2704 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2705 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002706 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002707 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2708 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2709 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2710 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002711 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002712 method_bitmap_size_ = 0;
2713 }
2714
2715 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002716 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002717 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002718 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2719 } else {
2720 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2721 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2722 if (type_ == kOatClassSomeCompiled) {
2723 method_bitmap_->SetBit(i);
2724 }
2725 }
2726 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002727}
2728
Brian Carlstrom265091e2013-01-30 14:08:26 -08002729size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2730 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002731 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2732 if (method_offset == 0) {
2733 return 0;
2734 }
2735 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002736}
2737
2738size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2739 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002740 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002741}
2742
2743size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002744 return sizeof(status_)
2745 + sizeof(type_)
2746 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2747 + method_bitmap_size_
2748 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002749}
2750
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002751bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002752 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002753 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002754 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002755 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002756 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002757 return false;
2758 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002759 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002760
Vladimir Markoe079e212016-05-25 12:49:49 +01002761 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002762 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002763 return false;
2764 }
2765 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002766
Brian Carlstromba150c32013-08-27 17:31:03 -07002767 if (method_bitmap_size_ != 0) {
2768 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002769 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002770 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002771 return false;
2772 }
2773 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002774
Vladimir Markoe079e212016-05-25 12:49:49 +01002775 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002776 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002777 return false;
2778 }
2779 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2780 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002781
Vladimir Markoe079e212016-05-25 12:49:49 +01002782 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002783 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002784 return false;
2785 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002786 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002787 return true;
2788}
2789
Brian Carlstrome24fa612011-09-29 00:53:55 -07002790} // namespace art