blob: eed9d117aecbf5139ffa5f7da3964ad76a3267ba [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"
Jeff Hao608f2ce2016-10-19 11:17:11 -070036#include "dexlayout.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "driver/compiler_driver.h"
38#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010039#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010042#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010043#include "linker/buffered_output_stream.h"
44#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000045#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000046#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/array.h"
48#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010049#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010051#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070052#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070053#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030055#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010056#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010057#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070058#include "verifier/method_verifier.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010059#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000060#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070061
62namespace art {
63
Vladimir Marko9bdf1082016-01-21 12:15:52 +000064namespace { // anonymous namespace
65
66typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
67
68const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
69 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
70}
71
Vladimir Markoe079e212016-05-25 12:49:49 +010072class ChecksumUpdatingOutputStream : public OutputStream {
73 public:
74 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
75 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
76
77 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
78 oat_header_->UpdateChecksum(buffer, byte_count);
79 return out_->WriteFully(buffer, byte_count);
80 }
81
82 off_t Seek(off_t offset, Whence whence) OVERRIDE {
83 return out_->Seek(offset, whence);
84 }
85
86 bool Flush() OVERRIDE {
87 return out_->Flush();
88 }
89
90 private:
91 OutputStream* const out_;
92 OatHeader* const oat_header_;
93};
94
Vladimir Marko0c737df2016-08-01 16:33:16 +010095inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
96 // We want to align the code rather than the preheader.
97 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
98 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
99 return aligned_code_offset - unaligned_code_offset;
100}
101
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000102} // anonymous namespace
103
104// Defines the location of the raw dex file to write.
105class OatWriter::DexFileSource {
106 public:
107 explicit DexFileSource(ZipEntry* zip_entry)
108 : type_(kZipEntry), source_(zip_entry) {
109 DCHECK(source_ != nullptr);
110 }
111
112 explicit DexFileSource(File* raw_file)
113 : type_(kRawFile), source_(raw_file) {
114 DCHECK(source_ != nullptr);
115 }
116
117 explicit DexFileSource(const uint8_t* dex_file)
118 : type_(kRawData), source_(dex_file) {
119 DCHECK(source_ != nullptr);
120 }
121
122 bool IsZipEntry() const { return type_ == kZipEntry; }
123 bool IsRawFile() const { return type_ == kRawFile; }
124 bool IsRawData() const { return type_ == kRawData; }
125
126 ZipEntry* GetZipEntry() const {
127 DCHECK(IsZipEntry());
128 DCHECK(source_ != nullptr);
129 return static_cast<ZipEntry*>(const_cast<void*>(source_));
130 }
131
132 File* GetRawFile() const {
133 DCHECK(IsRawFile());
134 DCHECK(source_ != nullptr);
135 return static_cast<File*>(const_cast<void*>(source_));
136 }
137
138 const uint8_t* GetRawData() const {
139 DCHECK(IsRawData());
140 DCHECK(source_ != nullptr);
141 return static_cast<const uint8_t*>(source_);
142 }
143
144 void Clear() {
145 type_ = kNone;
146 source_ = nullptr;
147 }
148
149 private:
150 enum Type {
151 kNone,
152 kZipEntry,
153 kRawFile,
154 kRawData,
155 };
156
157 Type type_;
158 const void* source_;
159};
160
Vladimir Marko49b0f452015-12-10 13:49:19 +0000161class OatWriter::OatClass {
162 public:
163 OatClass(size_t offset,
164 const dchecked_vector<CompiledMethod*>& compiled_methods,
165 uint32_t num_non_null_compiled_methods,
166 mirror::Class::Status status);
167 OatClass(OatClass&& src) = default;
168 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
169 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
170 size_t SizeOf() const;
171 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
172
173 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
174 return compiled_methods_[class_def_method_index];
175 }
176
177 // Offset of start of OatClass from beginning of OatHeader. It is
178 // used to validate file position when writing.
179 size_t offset_;
180
181 // CompiledMethods for each class_def_method_index, or null if no method is available.
182 dchecked_vector<CompiledMethod*> compiled_methods_;
183
184 // Offset from OatClass::offset_ to the OatMethodOffsets for the
185 // class_def_method_index. If 0, it means the corresponding
186 // CompiledMethod entry in OatClass::compiled_methods_ should be
187 // null and that the OatClass::type_ should be kOatClassBitmap.
188 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
189
190 // Data to write.
191
192 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
193 int16_t status_;
194
195 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
196 uint16_t type_;
197
198 uint32_t method_bitmap_size_;
199
200 // bit vector indexed by ClassDef method index. When
201 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
202 // method has an OatMethodOffsets in methods_offsets_, otherwise
203 // the entry was ommited to save space. If OatClassType::type_ is
204 // not is kOatClassBitmap, the bitmap will be null.
205 std::unique_ptr<BitVector> method_bitmap_;
206
207 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
208 // present in the OatClass. Note that some may be missing if
209 // OatClass::compiled_methods_ contains null values (and
210 // oat_method_offsets_offsets_from_oat_class_ should contain 0
211 // values in this case).
212 dchecked_vector<OatMethodOffsets> method_offsets_;
213 dchecked_vector<OatQuickMethodHeader> method_headers_;
214
215 private:
216 size_t GetMethodOffsetsRawSize() const {
217 return method_offsets_.size() * sizeof(method_offsets_[0]);
218 }
219
220 DISALLOW_COPY_AND_ASSIGN(OatClass);
221};
222
223class OatWriter::OatDexFile {
224 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 OatDexFile(const char* dex_file_location,
226 DexFileSource source,
227 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000228 OatDexFile(OatDexFile&& src) = default;
229
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000230 const char* GetLocation() const {
231 return dex_file_location_data_;
232 }
233
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000234 void ReserveClassOffsets(OatWriter* oat_writer);
235
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000237 bool Write(OatWriter* oat_writer, OutputStream* out) const;
238 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
239
240 // The source of the dex file.
241 DexFileSource source_;
242
243 // Whether to create the type lookup table.
244 CreateTypeLookupTable create_type_lookup_table_;
245
246 // Dex file size. Initialized when writing the dex file.
247 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248
249 // Offset of start of OatDexFile from beginning of OatHeader. It is
250 // used to validate file position when writing.
251 size_t offset_;
252
253 // Data to write.
254 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000256 uint32_t dex_file_location_checksum_;
257 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000258 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000259 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000260
261 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000262 dchecked_vector<uint32_t> class_offsets_;
263
264 private:
265 size_t GetClassOffsetsRawSize() const {
266 return class_offsets_.size() * sizeof(class_offsets_[0]);
267 }
268
269 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
270};
271
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100272#define DCHECK_OFFSET() \
273 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
274 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
275
276#define DCHECK_OFFSET_() \
277 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
278 << "file_offset=" << file_offset << " offset_=" << offset_
279
Jeff Hao608f2ce2016-10-19 11:17:11 -0700280OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000281 : write_state_(WriteState::kAddingDexFileSources),
282 timings_(timings),
283 raw_dex_files_(),
284 zip_archives_(),
285 zipped_dex_files_(),
286 zipped_dex_file_locations_(),
287 compiler_driver_(nullptr),
288 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800289 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000290 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100291 vdex_size_(0u),
292 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100293 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100294 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100295 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000296 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000297 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000298 bss_roots_offset_(0u),
299 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100300 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700301 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100302 size_vdex_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700303 size_dex_file_alignment_(0),
304 size_executable_offset_alignment_(0),
305 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700306 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700307 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100308 size_verifier_deps_(0),
309 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100310 size_quickening_info_(0),
311 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700312 size_interpreter_to_interpreter_bridge_(0),
313 size_interpreter_to_compiled_code_bridge_(0),
314 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800315 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700316 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700317 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700318 size_quick_to_interpreter_bridge_(0),
319 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100320 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700321 size_code_(0),
322 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100323 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100324 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700325 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700326 size_oat_dex_file_location_size_(0),
327 size_oat_dex_file_location_data_(0),
328 size_oat_dex_file_location_checksum_(0),
329 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000330 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000331 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000332 size_oat_lookup_table_alignment_(0),
333 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000334 size_oat_class_offsets_alignment_(0),
335 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700336 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700337 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700338 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100339 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000340 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700341 absolute_patch_locations_(),
342 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000343}
344
345bool OatWriter::AddDexFileSource(const char* filename,
346 const char* location,
347 CreateTypeLookupTable create_type_lookup_table) {
348 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
349 uint32_t magic;
350 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700351 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
352 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000353 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
354 return false;
355 } else if (IsDexMagic(magic)) {
356 // The file is open for reading, not writing, so it's OK to let the File destructor
357 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700358 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000359 oat_dex_files_.emplace_back(location,
360 DexFileSource(raw_dex_files_.back().get()),
361 create_type_lookup_table);
362 } else if (IsZipMagic(magic)) {
363 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
364 return false;
365 }
366 } else {
367 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
368 return false;
369 }
370 return true;
371}
372
373// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700374bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000375 const char* location,
376 CreateTypeLookupTable create_type_lookup_table) {
377 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
378 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700379 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000380 ZipArchive* zip_archive = zip_archives_.back().get();
381 if (zip_archive == nullptr) {
382 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
383 << error_msg;
384 return false;
385 }
386 for (size_t i = 0; ; ++i) {
387 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
388 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
389 if (entry == nullptr) {
390 break;
391 }
392 zipped_dex_files_.push_back(std::move(entry));
393 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
394 const char* full_location = zipped_dex_file_locations_.back().c_str();
395 oat_dex_files_.emplace_back(full_location,
396 DexFileSource(zipped_dex_files_.back().get()),
397 create_type_lookup_table);
398 }
399 if (zipped_dex_file_locations_.empty()) {
400 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
401 return false;
402 }
403 return true;
404}
405
406// Add dex file source from raw memory.
407bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
408 const char* location,
409 uint32_t location_checksum,
410 CreateTypeLookupTable create_type_lookup_table) {
411 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
412 if (data.size() < sizeof(DexFile::Header)) {
413 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
414 << data.size() << " File: " << location;
415 return false;
416 }
417 if (!ValidateDexFileHeader(data.data(), location)) {
418 return false;
419 }
420 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
421 if (data.size() < header->file_size_) {
422 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
423 << " file size from header: " << header->file_size_ << " File: " << location;
424 return false;
425 }
426
427 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
428 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
429 return true;
430}
431
432dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
433 dchecked_vector<const char*> locations;
434 locations.reserve(oat_dex_files_.size());
435 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
436 locations.push_back(oat_dex_file.GetLocation());
437 }
438 return locations;
439}
440
441bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100442 File* vdex_file,
443 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 InstructionSet instruction_set,
445 const InstructionSetFeatures* instruction_set_features,
446 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800447 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000448 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
449 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
450 CHECK(write_state_ == WriteState::kAddingDexFileSources);
451
David Brazdil7b49e6c2016-09-01 11:06:18 +0100452 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
453 if (!RecordOatDataOffset(oat_rodata)) {
454 return false;
455 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000456
457 std::unique_ptr<MemMap> dex_files_map;
458 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100459
460 // Initialize VDEX and OAT headers.
461 if (kIsVdexEnabled) {
462 size_vdex_header_ = sizeof(VdexFile::Header);
463 vdex_size_ = size_vdex_header_;
464 }
465 size_t oat_data_offset = InitOatHeader(instruction_set,
466 instruction_set_features,
467 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
468 key_value_store);
469 oat_size_ = InitOatDexFiles(oat_data_offset);
470
471 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
472
473 if (kIsVdexEnabled) {
474 std::unique_ptr<BufferedOutputStream> vdex_out(
475 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
476
477 // Write DEX files into VDEX, mmap and open them.
478 if (!WriteDexFiles(vdex_out.get(), vdex_file) ||
479 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
480 return false;
481 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100482 } else {
483 // Write DEX files into OAT, mmap and open them.
484 if (!WriteDexFiles(oat_rodata, vdex_file) ||
485 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
486 return false;
487 }
488
489 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
490 // difficult because we're not using the OutputStream directly.
491 if (!oat_dex_files_.empty()) {
492 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
493 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
494 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000496
David Brazdil7b49e6c2016-09-01 11:06:18 +0100497 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000498 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
499 return false;
500 }
501
David Brazdil7b49e6c2016-09-01 11:06:18 +0100502 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000503 for (OatDexFile& oat_dex_file : oat_dex_files_) {
504 oat_dex_file.ReserveClassOffsets(this);
505 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100506
David Brazdil7b49e6c2016-09-01 11:06:18 +0100507 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000508 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
509 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000510 }
511
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000512 *opened_dex_files_map = std::move(dex_files_map);
513 *opened_dex_files = std::move(dex_files);
514 write_state_ = WriteState::kPrepareLayout;
515 return true;
516}
517
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100518void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000519 CHECK(write_state_ == WriteState::kPrepareLayout);
520
Vladimir Marko944da602016-02-19 12:27:55 +0000521 relative_patcher_ = relative_patcher;
522 SetMultiOatRelativePatcherAdjustment();
523
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 if (compiling_boot_image_) {
525 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800526 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100527 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000528 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100529
David Brazdil7b49e6c2016-09-01 11:06:18 +0100530 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800531 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000532 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800533 offset = InitOatClasses(offset);
534 }
535 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000536 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100537 offset = InitOatMaps(offset);
538 }
539 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000540 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800541 offset = InitOatCode(offset);
542 }
543 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000544 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800545 offset = InitOatCodeDexFiles(offset);
546 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100547 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700548
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800549 if (!HasBootImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000550 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
551 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100552 }
553
Brian Carlstrome24fa612011-09-29 00:53:55 -0700554 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800555 if (compiling_boot_image_) {
556 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800558 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000559
560 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700561}
562
Ian Rogers0571d352011-11-03 19:51:38 -0700563OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700564}
565
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100566class OatWriter::DexMethodVisitor {
567 public:
568 DexMethodVisitor(OatWriter* writer, size_t offset)
569 : writer_(writer),
570 offset_(offset),
571 dex_file_(nullptr),
572 class_def_index_(DexFile::kDexNoIndex) {
573 }
574
575 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
576 DCHECK(dex_file_ == nullptr);
577 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
578 dex_file_ = dex_file;
579 class_def_index_ = class_def_index;
580 return true;
581 }
582
583 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
584
585 virtual bool EndClass() {
586 if (kIsDebugBuild) {
587 dex_file_ = nullptr;
588 class_def_index_ = DexFile::kDexNoIndex;
589 }
590 return true;
591 }
592
593 size_t GetOffset() const {
594 return offset_;
595 }
596
597 protected:
598 virtual ~DexMethodVisitor() { }
599
600 OatWriter* const writer_;
601
602 // The offset is usually advanced for each visited method by the derived class.
603 size_t offset_;
604
605 // The dex file and class def index are set in StartClass().
606 const DexFile* dex_file_;
607 size_t class_def_index_;
608};
609
610class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
611 public:
612 OatDexMethodVisitor(OatWriter* writer, size_t offset)
613 : DexMethodVisitor(writer, offset),
614 oat_class_index_(0u),
615 method_offsets_index_(0u) {
616 }
617
618 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
619 DexMethodVisitor::StartClass(dex_file, class_def_index);
620 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
621 method_offsets_index_ = 0u;
622 return true;
623 }
624
625 bool EndClass() {
626 ++oat_class_index_;
627 return DexMethodVisitor::EndClass();
628 }
629
630 protected:
631 size_t oat_class_index_;
632 size_t method_offsets_index_;
633};
634
635class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
636 public:
637 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
638 : DexMethodVisitor(writer, offset),
639 compiled_methods_(),
640 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000641 size_t num_classes = 0u;
642 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
643 num_classes += oat_dex_file.class_offsets_.size();
644 }
645 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100646 compiled_methods_.reserve(256u);
647 }
648
649 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
650 DexMethodVisitor::StartClass(dex_file, class_def_index);
651 compiled_methods_.clear();
652 num_non_null_compiled_methods_ = 0u;
653 return true;
654 }
655
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300656 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
657 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100658 // Fill in the compiled_methods_ array for methods that have a
659 // CompiledMethod. We track the number of non-null entries in
660 // num_non_null_compiled_methods_ since we only want to allocate
661 // OatMethodOffsets for the compiled methods.
662 uint32_t method_idx = it.GetMemberIndex();
663 CompiledMethod* compiled_method =
664 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
665 compiled_methods_.push_back(compiled_method);
666 if (compiled_method != nullptr) {
667 ++num_non_null_compiled_methods_;
668 }
669 return true;
670 }
671
672 bool EndClass() {
673 ClassReference class_ref(dex_file_, class_def_index_);
674 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
675 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700676 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100677 status = compiled_class->GetStatus();
678 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
679 status = mirror::Class::kStatusError;
680 } else {
681 status = mirror::Class::kStatusNotReady;
682 }
683
Vladimir Marko49b0f452015-12-10 13:49:19 +0000684 writer_->oat_classes_.emplace_back(offset_,
685 compiled_methods_,
686 num_non_null_compiled_methods_,
687 status);
688 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100689 return DexMethodVisitor::EndClass();
690 }
691
692 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000693 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100694 size_t num_non_null_compiled_methods_;
695};
696
697class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
698 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100699 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100700 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100701 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
702 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100703 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100704 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
705 }
706
707 bool EndClass() {
708 OatDexMethodVisitor::EndClass();
709 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100710 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100711 }
712 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100713 }
714
715 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700716 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000717 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
719
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100720 if (it.GetMethodCodeItem() != nullptr) {
721 current_quickening_info_offset_ += sizeof(uint32_t);
722 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723 if (compiled_method != nullptr) {
724 // Derived from CompiledMethod.
725 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100726
Vladimir Marko35831e82015-09-11 11:59:18 +0100727 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
728 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800729 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800730
David Srbecky009e2a62015-04-15 02:46:30 +0100731 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100732 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800733 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000734 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000735 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
736 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800737 // Duplicate methods, we want the same code for both of them so that the oat writer puts
738 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800739 } else {
740 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100741 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800742 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000743 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100744 quick_code_offset = dedupe_map_.GetOrCreate(
745 compiled_method,
746 [this, &deduped, compiled_method, &it, thumb_offset]() {
747 deduped = false;
748 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
749 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800750 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100751
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100752 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000753 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100754 // TODO: Should this be a hard failure?
755 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700756 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000757 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
758 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100759 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000760 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100761 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800762 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100763
Elliott Hughes956af0f2014-12-11 14:34:28 -0800764 // Update quick method header.
765 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
766 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800767 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Elliott Hughes956af0f2014-12-11 14:34:28 -0800768 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
769 // to 0-offset and we need to adjust it by code_offset.
770 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100771 if (!compiled_method->GetQuickCode().empty()) {
772 // If the code is compiled, we write the offset of the stack map relative
773 // to the code,
774 if (vmap_table_offset != 0u) {
775 vmap_table_offset += code_offset;
776 DCHECK_LT(vmap_table_offset, code_offset);
777 }
778 } else {
779 if (kIsVdexEnabled) {
780 // We write the offset in the .vdex file.
781 DCHECK_EQ(vmap_table_offset, 0u);
782 vmap_table_offset = current_quickening_info_offset_;
783 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
784 current_quickening_info_offset_ += map.size() * sizeof(map.front());
785 } else {
786 // We write the offset of the quickening info relative to the code.
787 vmap_table_offset += code_offset;
788 DCHECK_LT(vmap_table_offset, code_offset);
789 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800790 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800791 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
792 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
793 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100794 *method_header = OatQuickMethodHeader(vmap_table_offset,
795 frame_size_in_bytes,
796 core_spill_mask,
797 fp_spill_mask,
798 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100799
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000800 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800801 // Update offsets. (Checksum is updated when writing.)
802 offset_ += sizeof(*method_header); // Method header is prepended before code.
803 offset_ += code_size;
804 // Record absolute patch locations.
805 if (!compiled_method->GetPatches().empty()) {
806 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
807 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000808 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100809 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100810 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000811 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
812 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
813 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
814 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100815 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100816 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800817 }
Alex Light78382fa2014-06-06 15:45:32 -0700818
David Srbecky91cc06c2016-03-07 16:13:58 +0000819 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000820 // Exclude quickened dex methods (code_size == 0) since they have no native code.
821 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
822 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800823 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000824 debug::MethodDebugInfo info = debug::MethodDebugInfo();
825 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000826 info.dex_file = dex_file_;
827 info.class_def_index = class_def_index_;
828 info.dex_method_index = it.GetMemberIndex();
829 info.access_flags = it.GetMethodAccessFlags();
830 info.code_item = it.GetMethodCodeItem();
831 info.isa = compiled_method->GetInstructionSet();
832 info.deduped = deduped;
833 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
834 info.is_optimized = method_header->IsOptimized();
835 info.is_code_address_text_relative = true;
836 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
837 info.code_size = code_size;
838 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
839 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
840 info.cfi = compiled_method->GetCFIInfo();
841 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100842 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100843
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100844 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
845 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
846 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100847 ++method_offsets_index_;
848 }
849
850 return true;
851 }
852
853 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000854 struct CodeOffsetsKeyComparator {
855 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100856 // Code is deduplicated by CompilerDriver, compare only data pointers.
857 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
858 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000859 }
860 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100861 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
862 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000863 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100864 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
865 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000866 }
867 return false;
868 }
869 };
870
David Srbecky009e2a62015-04-15 02:46:30 +0100871 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
872 const ClassDataItemIterator& it,
873 uint32_t thumb_offset) {
874 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100875 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100876 offset_ += CodeAlignmentSize(offset_, *compiled_method);
877 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100878 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
879 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
880 }
881
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100882 // Deduplication is already done on a pointer basis by the compiler driver,
883 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100884 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100885
David Srbecky009e2a62015-04-15 02:46:30 +0100886 // Cache of compiler's --debuggable option.
887 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100888
889 // Offset in the vdex file for the quickening info.
890 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100891};
892
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100893class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
894 public:
895 InitMapMethodVisitor(OatWriter* writer, size_t offset)
896 : OatDexMethodVisitor(writer, offset) {
897 }
898
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700899 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700900 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000901 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100902 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
903
904 if (compiled_method != nullptr) {
905 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100906 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
907 // be in the vdex file.
908 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
909 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100910
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100911 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
912 uint32_t map_size = map.size() * sizeof(map[0]);
913 if (map_size != 0u) {
914 size_t offset = dedupe_map_.GetOrCreate(
915 map.data(),
916 [this, map_size]() {
917 uint32_t new_offset = offset_;
918 offset_ += map_size;
919 return new_offset;
920 });
921 // Code offset is not initialized yet, so set the map offset to 0u-offset.
922 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
923 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
924 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100925 }
926 ++method_offsets_index_;
927 }
928
929 return true;
930 }
931
932 private:
933 // Deduplication is already done on a pointer basis by the compiler driver,
934 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100935 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100936};
937
938class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
939 public:
940 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800941 : OatDexMethodVisitor(writer, offset),
942 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100943 }
944
945 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700946 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800947 const DexFile::TypeId& type_id =
948 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
949 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
950 // Skip methods that are not in the image.
951 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
952 return true;
953 }
954
Vladimir Marko49b0f452015-12-10 13:49:19 +0000955 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100956 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
957
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800958 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 if (compiled_method != nullptr) {
960 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
961 offsets = oat_class->method_offsets_[method_offsets_index_];
962 ++method_offsets_index_;
963 }
964
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100965 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100966 // Unchecked as we hold mutator_lock_ on entry.
967 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800968 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700969 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
970 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800971 ArtMethod* method;
972 if (writer_->HasBootImage()) {
973 const InvokeType invoke_type = it.GetMethodInvokeType(
974 dex_file_->GetClassDef(class_def_index_));
975 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
976 *dex_file_,
977 it.GetMemberIndex(),
978 dex_cache,
979 ScopedNullHandle<mirror::ClassLoader>(),
980 nullptr,
981 invoke_type);
982 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700983 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -0700984 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800985 soa.Self()->AssertPendingException();
986 mirror::Throwable* exc = soa.Self()->GetException();
987 std::string dump = exc->Dump();
988 LOG(FATAL) << dump;
989 UNREACHABLE();
990 }
991 } else {
992 // Should already have been resolved by the compiler, just peek into the dex cache.
993 // It may not be resolved if the class failed to verify, in this case, don't set the
994 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
995 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700996 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800997 if (method != nullptr &&
998 compiled_method != nullptr &&
999 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001000 method->SetEntryPointFromQuickCompiledCodePtrSize(
1001 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1002 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001003
1004 return true;
1005 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001006
1007 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001008 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001009};
1010
1011class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1012 public:
1013 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001014 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001015 : OatDexMethodVisitor(writer, relative_offset),
1016 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001017 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001018 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001019 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001020 class_linker_(Runtime::Current()->GetClassLinker()),
1021 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001022 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001023 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001024 // If we're creating the image, the address space must be ready so that we can apply patches.
1025 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001026 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001027 }
1028
Vladimir Markof4da6752014-08-01 19:04:18 +01001029 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001030 }
1031
1032 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001033 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001034 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1035 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001036 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001037 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001038 }
1039 return true;
1040 }
1041
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001042 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001043 bool result = OatDexMethodVisitor::EndClass();
1044 if (oat_class_index_ == writer_->oat_classes_.size()) {
1045 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001046 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001047 if (UNLIKELY(offset_ == 0u)) {
1048 PLOG(ERROR) << "Failed to write final relative call thunks";
1049 result = false;
1050 }
1051 }
1052 return result;
1053 }
1054
1055 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001056 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001057 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001058 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1059
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001060 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001061 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001062 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001063 size_t file_offset = file_offset_;
1064 OutputStream* out = out_;
1065
Vladimir Marko35831e82015-09-11 11:59:18 +01001066 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1067 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001068
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001069 // Deduplicate code arrays.
1070 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1071 if (method_offsets.code_offset_ > offset_) {
1072 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1073 if (offset_ == 0u) {
1074 ReportWriteFailure("relative call thunk", it);
1075 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001076 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001077 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1078 if (alignment_size != 0) {
1079 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001080 ReportWriteFailure("code alignment padding", it);
1081 return false;
1082 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001083 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001084 DCHECK_OFFSET_();
1085 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001086 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001087 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1088 DCHECK_EQ(method_offsets.code_offset_,
1089 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001090 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001091 const OatQuickMethodHeader& method_header =
1092 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001093 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001094 ReportWriteFailure("method header", it);
1095 return false;
1096 }
1097 writer_->size_method_header_ += sizeof(method_header);
1098 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001099 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001100
1101 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001102 patched_code_.assign(quick_code.begin(), quick_code.end());
1103 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001104 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001105 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001106 switch (patch.GetType()) {
1107 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001108 // NOTE: Relative calls across oat files are not supported.
1109 uint32_t target_offset = GetTargetOffset(patch);
1110 writer_->relative_patcher_->PatchCall(&patched_code_,
1111 literal_offset,
1112 offset_ + literal_offset,
1113 target_offset);
1114 break;
1115 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001116 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001117 uint32_t target_offset = GetDexCacheOffset(patch);
1118 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1119 patch,
1120 offset_ + literal_offset,
1121 target_offset);
1122 break;
1123 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001124 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001125 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1126 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1127 patch,
1128 offset_ + literal_offset,
1129 target_offset);
1130 break;
1131 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001132 case LinkerPatch::Type::kStringBssEntry: {
1133 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1134 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1135 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1136 patch,
1137 offset_ + literal_offset,
1138 target_offset);
1139 break;
1140 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001141 case LinkerPatch::Type::kTypeRelative: {
1142 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1143 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1144 patch,
1145 offset_ + literal_offset,
1146 target_offset);
1147 break;
1148 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001149 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001150 uint32_t target_offset = GetTargetOffset(patch);
1151 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1152 break;
1153 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001154 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001155 ArtMethod* method = GetTargetMethod(patch);
1156 PatchMethodAddress(&patched_code_, literal_offset, method);
1157 break;
1158 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001159 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001160 mirror::String* string = GetTargetString(patch);
1161 PatchObjectAddress(&patched_code_, literal_offset, string);
1162 break;
1163 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001164 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001165 mirror::Class* type = GetTargetType(patch);
1166 PatchObjectAddress(&patched_code_, literal_offset, type);
1167 break;
1168 }
1169 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001170 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001171 break;
1172 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001173 }
1174 }
1175 }
1176
Vladimir Markoe079e212016-05-25 12:49:49 +01001177 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001178 ReportWriteFailure("method code", it);
1179 return false;
1180 }
1181 writer_->size_code_ += code_size;
1182 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001183 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001184 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001185 ++method_offsets_index_;
1186 }
1187
1188 return true;
1189 }
1190
1191 private:
1192 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001193 const size_t file_offset_;
1194 const ScopedObjectAccess soa_;
1195 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001196 ClassLinker* const class_linker_;
1197 mirror::DexCache* dex_cache_;
1198 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001199
1200 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1201 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001202 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001203 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001204
Mathieu Chartiere401d142015-04-22 13:56:20 -07001205 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001206 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001207 MethodReference ref = patch.TargetMethod();
1208 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001209 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1210 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 ArtMethod* method = dex_cache->GetResolvedMethod(
1212 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001213 CHECK(method != nullptr);
1214 return method;
1215 }
1216
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001217 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001218 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1219 // If there's no new compiled code, either we're compiling an app and the target method
1220 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001221 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001222 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001223 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001224 PointerSize size =
1225 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001226 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1227 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001228 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001229 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1230 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1231 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1232 target_offset = PointerToLowMemUInt32(oat_code_offset);
1233 } else {
1234 target_offset = target->IsNative()
1235 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1236 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1237 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001238 }
1239 return target_offset;
1240 }
1241
Vladimir Marko052164a2016-04-27 13:54:18 +01001242 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001243 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001244 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001245 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001246 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1247 }
1248
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001249 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001250 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001251 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1252 CHECK(type != nullptr);
1253 return type;
1254 }
1255
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001256 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001257 ScopedObjectAccessUnchecked soa(Thread::Current());
1258 StackHandleScope<1> hs(soa.Self());
1259 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1260 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1261 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1262 patch.TargetStringIndex(),
1263 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001264 DCHECK(string != nullptr);
1265 DCHECK(writer_->HasBootImage() ||
1266 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1267 return string;
1268 }
1269
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001270 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001271 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001272 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1273 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1274 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1275 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001276 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001277 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001278 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1279 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001280 }
1281 }
1282
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001283 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001284 DCHECK(writer_->HasBootImage());
1285 object = writer_->image_writer_->GetImageAddress(object);
1286 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1287 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1288 // TODO: Clean up offset types. The target offset must be treated as signed.
1289 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1290 }
1291
Vladimir Markof4da6752014-08-01 19:04:18 +01001292 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001293 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001294 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001295 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001296 } else {
1297 // NOTE: We're using linker patches for app->boot references when the image can
1298 // be relocated and therefore we need to emit .oat_patches. We're not using this
1299 // for app->app references, so check that the object is in the image space.
1300 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001301 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001302 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001303 uint32_t address = PointerToLowMemUInt32(object);
1304 DCHECK_LE(offset + 4, code->size());
1305 uint8_t* data = &(*code)[offset];
1306 data[0] = address & 0xffu;
1307 data[1] = (address >> 8) & 0xffu;
1308 data[2] = (address >> 16) & 0xffu;
1309 data[3] = (address >> 24) & 0xffu;
1310 }
1311
Mathieu Chartiere401d142015-04-22 13:56:20 -07001312 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001313 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001314 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001315 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001316 } else if (kIsDebugBuild) {
1317 // NOTE: We're using linker patches for app->boot references when the image can
1318 // be relocated and therefore we need to emit .oat_patches. We're not using this
1319 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001320 std::vector<gc::space::ImageSpace*> image_spaces =
1321 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1322 bool contains_method = false;
1323 for (gc::space::ImageSpace* image_space : image_spaces) {
1324 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1325 contains_method |=
1326 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1327 }
1328 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001329 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001330 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001331 uint32_t address = PointerToLowMemUInt32(method);
1332 DCHECK_LE(offset + 4, code->size());
1333 uint8_t* data = &(*code)[offset];
1334 data[0] = address & 0xffu;
1335 data[1] = (address >> 8) & 0xffu;
1336 data[2] = (address >> 16) & 0xffu;
1337 data[3] = (address >> 24) & 0xffu;
1338 }
1339
Vladimir Markof4da6752014-08-01 19:04:18 +01001340 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001341 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001342 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001343 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001344 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1345 // TODO: Clean up offset types.
1346 // The target_offset must be treated as signed for cross-oat patching.
1347 const void* target = reinterpret_cast<const void*>(
1348 writer_->image_writer_->GetOatDataBegin(oat_index) +
1349 static_cast<int32_t>(target_offset));
1350 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001351 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001352 DCHECK_LE(offset + 4, code->size());
1353 uint8_t* data = &(*code)[offset];
1354 data[0] = address & 0xffu;
1355 data[1] = (address >> 8) & 0xffu;
1356 data[2] = (address >> 16) & 0xffu;
1357 data[3] = (address >> 24) & 0xffu;
1358 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001359};
1360
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001361class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1362 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001363 WriteMapMethodVisitor(OatWriter* writer,
1364 OutputStream* out,
1365 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001366 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001367 : OatDexMethodVisitor(writer, relative_offset),
1368 out_(out),
1369 file_offset_(file_offset) {
1370 }
1371
1372 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001373 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001374 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1375
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001376 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001377 size_t file_offset = file_offset_;
1378 OutputStream* out = out_;
1379
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001380 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1381 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001382 ++method_offsets_index_;
1383
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001384 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1385 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1386 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001387 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001388
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001389 // If vdex is enabled, only emit the map for compiled code. The quickening info
1390 // is emitted in the vdex already.
1391 if (map_offset != 0u &&
1392 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001393 // Transform map_offset to actual oat data offset.
1394 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1395 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001396 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001397
1398 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1399 size_t map_size = map.size() * sizeof(map[0]);
1400 if (map_offset == offset_) {
1401 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001402 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001403 ReportWriteFailure(it);
1404 return false;
1405 }
1406 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001407 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001408 }
1409 DCHECK_OFFSET_();
1410 }
1411
1412 return true;
1413 }
1414
1415 private:
1416 OutputStream* const out_;
1417 size_t const file_offset_;
1418
1419 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001420 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001421 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001422 }
1423};
1424
1425// Visit all methods from all classes in all dex files with the specified visitor.
1426bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1427 for (const DexFile* dex_file : *dex_files_) {
1428 const size_t class_def_count = dex_file->NumClassDefs();
1429 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1430 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1431 return false;
1432 }
1433 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001434 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001435 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001436 ClassDataItemIterator it(*dex_file, class_data);
1437 while (it.HasNextStaticField()) {
1438 it.Next();
1439 }
1440 while (it.HasNextInstanceField()) {
1441 it.Next();
1442 }
1443 size_t class_def_method_index = 0u;
1444 while (it.HasNextDirectMethod()) {
1445 if (!visitor->VisitMethod(class_def_method_index, it)) {
1446 return false;
1447 }
1448 ++class_def_method_index;
1449 it.Next();
1450 }
1451 while (it.HasNextVirtualMethod()) {
1452 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1453 return false;
1454 }
1455 ++class_def_method_index;
1456 it.Next();
1457 }
1458 }
1459 if (UNLIKELY(!visitor->EndClass())) {
1460 return false;
1461 }
1462 }
1463 }
1464 return true;
1465}
1466
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001467size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1468 const InstructionSetFeatures* instruction_set_features,
1469 uint32_t num_dex_files,
1470 SafeMap<std::string, std::string>* key_value_store) {
1471 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1472 oat_header_.reset(OatHeader::Create(instruction_set,
1473 instruction_set_features,
1474 num_dex_files,
1475 key_value_store));
1476 size_oat_header_ += sizeof(OatHeader);
1477 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001478 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001479}
1480
1481size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001482 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1483 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001484 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001485 oat_dex_file.offset_ = offset;
1486 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001487 }
1488 return offset;
1489}
1490
Brian Carlstrom389efb02012-01-11 12:06:26 -08001491size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001492 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001493 InitOatClassesMethodVisitor visitor(this, offset);
1494 bool success = VisitDexMethods(&visitor);
1495 CHECK(success);
1496 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001497
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001498 // Update oat_dex_files_.
1499 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001500 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1501 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001502 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001503 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001504 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001505 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001506 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001507 CHECK(oat_class_it == oat_classes_.end());
1508
1509 return offset;
1510}
1511
1512size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001513 InitMapMethodVisitor visitor(this, offset);
1514 bool success = VisitDexMethods(&visitor);
1515 DCHECK(success);
1516 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001517
Brian Carlstrome24fa612011-09-29 00:53:55 -07001518 return offset;
1519}
1520
1521size_t OatWriter::InitOatCode(size_t offset) {
1522 // calculate the offsets within OatHeader to executable code
1523 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001524 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001525 // required to be on a new page boundary
1526 offset = RoundUp(offset, kPageSize);
1527 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001528 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001529 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001530 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001531
Ian Rogers848871b2013-08-05 10:56:33 -07001532 #define DO_TRAMPOLINE(field, fn_name) \
1533 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001534 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1535 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001536 (field) = compiler_driver_->Create ## fn_name(); \
1537 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001538
Ian Rogers848871b2013-08-05 10:56:33 -07001539 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001540 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001541 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001542 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1543 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001544
Ian Rogers848871b2013-08-05 10:56:33 -07001545 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001546 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001547 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1548 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1549 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001550 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001551 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001552 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001553 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001554 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001555 return offset;
1556}
1557
1558size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001559 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1560 bool success = VisitDexMethods(&code_visitor);
1561 DCHECK(success);
1562 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001563
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001564 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001565 InitImageMethodVisitor image_visitor(this, offset);
1566 success = VisitDexMethods(&image_visitor);
1567 DCHECK(success);
1568 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001569 }
Logan Chien8b977d32012-02-21 19:14:55 +08001570
Brian Carlstrome24fa612011-09-29 00:53:55 -07001571 return offset;
1572}
1573
Vladimir Markoaad75c62016-10-03 08:46:48 +00001574void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1575 DCHECK(!HasBootImage());
1576
1577 // Allocate space for app dex cache arrays in the .bss section.
1578 bss_start_ = RoundUp(oat_size_, kPageSize);
1579 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1580 bss_size_ = 0u;
1581 for (const DexFile* dex_file : *dex_files_) {
1582 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1583 DexCacheArraysLayout layout(pointer_size, dex_file);
1584 bss_size_ += layout.Size();
1585 }
1586
1587 bss_roots_offset_ = bss_size_;
1588
1589 // Prepare offsets for .bss String entries.
1590 for (auto& entry : bss_string_entries_) {
1591 DCHECK_EQ(entry.second, 0u);
1592 entry.second = bss_start_ + bss_size_;
1593 bss_size_ += sizeof(GcRoot<mirror::String>);
1594 }
1595}
1596
David Srbeckybc90fd02015-04-22 19:40:27 +01001597bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001598 CHECK(write_state_ == WriteState::kWriteRoData);
1599
Vladimir Markoe079e212016-05-25 12:49:49 +01001600 // Wrap out to update checksum with each write.
1601 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1602 out = &checksum_updating_out;
1603
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001604 if (!WriteClassOffsets(out)) {
1605 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001606 return false;
1607 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001608
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001609 if (!WriteClasses(out)) {
1610 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001611 return false;
1612 }
1613
Vladimir Markof4da6752014-08-01 19:04:18 +01001614 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001615 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001616 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001617 return false;
1618 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001619 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001620 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001621 relative_offset = WriteMaps(out, file_offset, relative_offset);
1622 if (relative_offset == 0) {
1623 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1624 return false;
1625 }
1626
David Srbeckybc90fd02015-04-22 19:40:27 +01001627 // Write padding.
1628 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1629 relative_offset += size_executable_offset_alignment_;
1630 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1631 size_t expected_file_offset = file_offset + relative_offset;
1632 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1633 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1634 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1635 return 0;
1636 }
1637 DCHECK_OFFSET();
1638
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001639 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001640 return true;
1641}
1642
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001643class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1644 public:
1645 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1646 : DexMethodVisitor(writer, offset),
1647 out_(out),
1648 written_bytes_(0u) {}
1649
1650 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1651 const ClassDataItemIterator& it) {
1652 if (it.GetMethodCodeItem() == nullptr) {
1653 // No CodeItem. Native or abstract method.
1654 return true;
1655 }
1656
1657 uint32_t method_idx = it.GetMemberIndex();
1658 CompiledMethod* compiled_method =
1659 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1660
1661 uint32_t length = 0;
1662 const uint8_t* data = nullptr;
1663 // VMap only contains quickening info if this method is not compiled.
1664 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1665 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1666 data = map.data();
1667 length = map.size() * sizeof(map.front());
1668 }
1669
1670 if (!out_->WriteFully(&length, sizeof(length)) ||
1671 !out_->WriteFully(data, length)) {
1672 PLOG(ERROR) << "Failed to write quickening info for "
1673 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1674 return false;
1675 }
1676 offset_ += sizeof(length) + length;
1677 written_bytes_ += sizeof(length) + length;
1678 return true;
1679 }
1680
1681 size_t GetNumberOfWrittenBytes() const {
1682 return written_bytes_;
1683 }
1684
1685 private:
1686 OutputStream* const out_;
1687 size_t written_bytes_;
1688};
1689
1690bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1691 if (!kIsVdexEnabled) {
1692 return true;
1693 }
1694
1695 size_t initial_offset = vdex_size_;
1696 size_t start_offset = RoundUp(initial_offset, 4u);
1697
1698 vdex_size_ = start_offset;
1699 vdex_quickening_info_offset_ = vdex_size_;
1700 size_quickening_info_alignment_ = start_offset - initial_offset;
1701
1702 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1703 if (actual_offset != static_cast<off_t>(start_offset)) {
1704 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1705 << " Expected: " << start_offset
1706 << " Output: " << vdex_out->GetLocation();
1707 return false;
1708 }
1709
1710 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1711 if (!VisitDexMethods(&visitor)) {
1712 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1713 return false;
1714 }
1715
1716 if (!vdex_out->Flush()) {
1717 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1718 << " File: " << vdex_out->GetLocation();
1719 return false;
1720 }
1721
1722 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1723 vdex_size_ += size_quickening_info_;
1724 return true;
1725}
1726
David Brazdil5d5a36b2016-09-14 15:34:10 +01001727bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1728 if (!kIsVdexEnabled) {
1729 return true;
1730 }
1731
1732 if (verifier_deps == nullptr) {
1733 // Nothing to write. Record the offset, but no need
1734 // for alignment.
1735 vdex_verifier_deps_offset_ = vdex_size_;
1736 return true;
1737 }
1738
1739 size_t initial_offset = vdex_size_;
1740 size_t start_offset = RoundUp(initial_offset, 4u);
1741
1742 vdex_size_ = start_offset;
1743 vdex_verifier_deps_offset_ = vdex_size_;
1744 size_verifier_deps_alignment_ = start_offset - initial_offset;
1745
1746 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1747 if (actual_offset != static_cast<off_t>(start_offset)) {
1748 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1749 << " Expected: " << start_offset
1750 << " Output: " << vdex_out->GetLocation();
1751 return false;
1752 }
1753
1754 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001755 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001756
1757 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1758 PLOG(ERROR) << "Failed to write verifier deps."
1759 << " File: " << vdex_out->GetLocation();
1760 return false;
1761 }
1762 if (!vdex_out->Flush()) {
1763 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1764 << " File: " << vdex_out->GetLocation();
1765 return false;
1766 }
1767
1768 size_verifier_deps_ = buffer.size();
1769 vdex_size_ += size_verifier_deps_;
1770 return true;
1771}
1772
David Srbeckybc90fd02015-04-22 19:40:27 +01001773bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001774 CHECK(write_state_ == WriteState::kWriteText);
1775
Vladimir Markoe079e212016-05-25 12:49:49 +01001776 // Wrap out to update checksum with each write.
1777 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1778 out = &checksum_updating_out;
1779
Vladimir Marko944da602016-02-19 12:27:55 +00001780 SetMultiOatRelativePatcherAdjustment();
1781
David Srbeckybc90fd02015-04-22 19:40:27 +01001782 const size_t file_offset = oat_data_offset_;
1783 size_t relative_offset = oat_header_->GetExecutableOffset();
1784 DCHECK_OFFSET();
1785
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001786 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001787 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001788 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001789 return false;
1790 }
1791
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001792 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1793 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001794 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001795 return false;
1796 }
1797
Vladimir Markof4da6752014-08-01 19:04:18 +01001798 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001799 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001800 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1801 return false;
1802 }
1803
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001804 if (kIsDebugBuild) {
1805 uint32_t size_total = 0;
1806 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001807 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1808 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001809
David Brazdil7b49e6c2016-09-01 11:06:18 +01001810 DO_STAT(size_vdex_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001811 DO_STAT(size_dex_file_alignment_);
1812 DO_STAT(size_executable_offset_alignment_);
1813 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001814 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001815 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001816 DO_STAT(size_verifier_deps_);
1817 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001818 DO_STAT(size_quickening_info_);
1819 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001820 DO_STAT(size_interpreter_to_interpreter_bridge_);
1821 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1822 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001823 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001824 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001825 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001826 DO_STAT(size_quick_to_interpreter_bridge_);
1827 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001828 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001829 DO_STAT(size_code_);
1830 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001831 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001832 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001833 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001834 DO_STAT(size_oat_dex_file_location_size_);
1835 DO_STAT(size_oat_dex_file_location_data_);
1836 DO_STAT(size_oat_dex_file_location_checksum_);
1837 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001838 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001839 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001840 DO_STAT(size_oat_lookup_table_alignment_);
1841 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001842 DO_STAT(size_oat_class_offsets_alignment_);
1843 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001844 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001845 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001846 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001847 DO_STAT(size_oat_class_method_offsets_);
1848 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001849
David Brazdil7b49e6c2016-09-01 11:06:18 +01001850 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1851
1852 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1853 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001854 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001855
David Brazdil7b49e6c2016-09-01 11:06:18 +01001856 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1857 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001858
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001859 write_state_ = WriteState::kWriteHeader;
1860 return true;
1861}
1862
1863bool OatWriter::WriteHeader(OutputStream* out,
1864 uint32_t image_file_location_oat_checksum,
1865 uintptr_t image_file_location_oat_begin,
1866 int32_t image_patch_delta) {
1867 CHECK(write_state_ == WriteState::kWriteHeader);
1868
1869 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1870 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001871 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001872 CHECK_EQ(image_patch_delta, 0);
1873 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1874 } else {
1875 CHECK_ALIGNED(image_patch_delta, kPageSize);
1876 oat_header_->SetImagePatchDelta(image_patch_delta);
1877 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001878 oat_header_->UpdateChecksumWithHeaderData();
1879
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001880 const size_t file_offset = oat_data_offset_;
1881
1882 off_t current_offset = out->Seek(0, kSeekCurrent);
1883 if (current_offset == static_cast<off_t>(-1)) {
1884 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1885 return false;
1886 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001887 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001888 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1889 return false;
1890 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001891 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001892
1893 // Flush all other data before writing the header.
1894 if (!out->Flush()) {
1895 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1896 return false;
1897 }
1898 // Write the header.
1899 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001900 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001901 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1902 return false;
1903 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001904 // Flush the header data.
1905 if (!out->Flush()) {
1906 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001907 return false;
1908 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001909
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001910 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1911 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1912 return false;
1913 }
1914 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1915
1916 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001917 return true;
1918}
1919
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001920bool OatWriter::WriteClassOffsets(OutputStream* out) {
1921 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1922 if (oat_dex_file.class_offsets_offset_ != 0u) {
1923 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1924 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1925 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1926 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1927 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001928 return false;
1929 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001930 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1931 return false;
1932 }
1933 }
1934 }
1935 return true;
1936}
1937
1938bool OatWriter::WriteClasses(OutputStream* out) {
1939 for (OatClass& oat_class : oat_classes_) {
1940 if (!oat_class.Write(this, out, oat_data_offset_)) {
1941 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1942 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001943 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001944 }
1945 return true;
1946}
1947
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001948size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001949 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001950 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1951 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1952 return 0;
1953 }
1954 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001955 size_vmap_table_ = relative_offset - vmap_tables_offset;
1956
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001957 return relative_offset;
1958}
1959
1960size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001961 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001962 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001963
Ian Rogers848871b2013-08-05 10:56:33 -07001964 #define DO_TRAMPOLINE(field) \
1965 do { \
1966 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1967 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001968 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001969 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001970 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001971 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001972 return false; \
1973 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001974 size_ ## field += (field)->size(); \
1975 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001976 DCHECK_OFFSET(); \
1977 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001978
Ian Rogers848871b2013-08-05 10:56:33 -07001979 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001980 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001981 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001982 DO_TRAMPOLINE(quick_resolution_trampoline_);
1983 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1984 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001985 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001986 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001987}
1988
Ian Rogers3d504072014-03-01 09:16:49 -08001989size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001990 const size_t file_offset,
1991 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001992 #define VISIT(VisitorType) \
1993 do { \
1994 VisitorType visitor(this, out, file_offset, relative_offset); \
1995 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1996 return 0; \
1997 } \
1998 relative_offset = visitor.GetOffset(); \
1999 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002000
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002001 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002002
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002003 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002004
Vladimir Markob163bb72015-03-31 21:49:49 +01002005 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2006 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2007 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2008
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002009 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002010}
2011
Vladimir Marko944da602016-02-19 12:27:55 +00002012bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002013 // Get the elf file offset of the oat file.
2014 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2015 if (raw_file_offset == static_cast<off_t>(-1)) {
2016 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2017 return false;
2018 }
2019 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2020 return true;
2021}
2022
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002023bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2024 // Read the dex file header and perform minimal verification.
2025 uint8_t raw_header[sizeof(DexFile::Header)];
2026 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2027 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2028 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2029 return false;
2030 }
2031 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2032 return false;
2033 }
2034
2035 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2036 oat_dex_file->dex_file_size_ = header->file_size_;
2037 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2038 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2039 return true;
2040}
2041
2042bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2043 if (!DexFile::IsMagicValid(raw_header)) {
2044 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2045 return false;
2046 }
2047 if (!DexFile::IsVersionValid(raw_header)) {
2048 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2049 return false;
2050 }
2051 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2052 if (header->file_size_ < sizeof(DexFile::Header)) {
2053 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2054 << " File: " << location;
2055 return false;
2056 }
2057 return true;
2058}
2059
David Brazdil7b49e6c2016-09-01 11:06:18 +01002060bool OatWriter::WriteDexFiles(OutputStream* out, File* file) {
2061 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002062
David Brazdil7b49e6c2016-09-01 11:06:18 +01002063 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002064
2065 // Write dex files.
2066 for (OatDexFile& oat_dex_file : oat_dex_files_) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002067 if (!WriteDexFile(out, file, &oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002068 return false;
2069 }
2070 }
2071
2072 // Close sources.
2073 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2074 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2075 }
2076 zipped_dex_files_.clear();
2077 zip_archives_.clear();
2078 raw_dex_files_.clear();
2079 return true;
2080}
2081
David Brazdil7b49e6c2016-09-01 11:06:18 +01002082bool OatWriter::WriteDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2083 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002084 return false;
2085 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002086 if (profile_compilation_info_ != nullptr) {
2087 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2088 return false;
2089 }
2090 } else if (oat_dex_file->source_.IsZipEntry()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002091 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002092 return false;
2093 }
2094 } else if (oat_dex_file->source_.IsRawFile()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002095 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002096 return false;
2097 }
2098 } else {
2099 DCHECK(oat_dex_file->source_.IsRawData());
David Brazdil7b49e6c2016-09-01 11:06:18 +01002100 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002101 return false;
2102 }
2103 }
2104
2105 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002106 if (kIsVdexEnabled) {
2107 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2108 vdex_size_ += oat_dex_file->dex_file_size_;
2109 } else {
2110 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2111 oat_size_ += oat_dex_file->dex_file_size_;
2112 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002113 size_dex_file_ += oat_dex_file->dex_file_size_;
2114 return true;
2115}
2116
2117bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2118 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002119 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2120 size_t start_offset = RoundUp(initial_offset, 4);
2121 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2122 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002123
2124 // Seek to the start of the dex file and flush any pending operations in the stream.
2125 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002126 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2127 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002128 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002129 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002130 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2131 return false;
2132 }
2133 if (!out->Flush()) {
2134 PLOG(ERROR) << "Failed to flush before writing dex file."
2135 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2136 return false;
2137 }
2138 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002139 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002140 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002141 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002142 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2143 return false;
2144 }
2145
David Brazdil7b49e6c2016-09-01 11:06:18 +01002146 if (kIsVdexEnabled) {
2147 vdex_size_ = start_offset;
2148 } else {
2149 oat_size_ = start_offset;
2150 }
2151 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002152 return true;
2153}
2154
Jeff Hao608f2ce2016-10-19 11:17:11 -07002155bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2156 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2157 std::string error_msg;
2158 std::string location(oat_dex_file->GetLocation());
2159 std::unique_ptr<const DexFile> dex_file;
2160 if (oat_dex_file->source_.IsZipEntry()) {
2161 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2162 std::unique_ptr<MemMap> mem_map(
2163 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2164 dex_file = DexFile::Open(location,
2165 zip_entry->GetCrc32(),
2166 std::move(mem_map),
2167 /* verify */ true,
2168 /* verify_checksum */ true,
2169 &error_msg);
2170 } else {
2171 DCHECK(oat_dex_file->source_.IsRawFile());
2172 File* raw_file = oat_dex_file->source_.GetRawFile();
2173 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2174 }
2175 Options options;
2176 options.output_to_memmap_ = true;
2177 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2178 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2179 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
2180 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin())) {
2181 return false;
2182 }
2183 // Set the checksum of the new oat dex file to be the original file's checksum.
2184 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2185 return true;
2186}
2187
David Brazdil7b49e6c2016-09-01 11:06:18 +01002188bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002189 File* file,
2190 OatDexFile* oat_dex_file,
2191 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002192 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2193 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002194
2195 // Extract the dex file and get the extracted size.
2196 std::string error_msg;
2197 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2198 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2199 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2200 return false;
2201 }
2202 if (file->Flush() != 0) {
2203 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2204 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2205 return false;
2206 }
2207 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2208 if (extracted_end == static_cast<off_t>(-1)) {
2209 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2210 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2211 return false;
2212 }
2213 if (extracted_end < static_cast<off_t>(start_offset)) {
2214 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2215 << " Start: " << start_offset
2216 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2217 return false;
2218 }
2219 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2220 if (extracted_size < sizeof(DexFile::Header)) {
2221 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2222 << extracted_size << " File: " << oat_dex_file->GetLocation();
2223 return false;
2224 }
2225
2226 // Read the dex file header and extract required data to OatDexFile.
2227 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2228 if (actual_offset != static_cast<off_t>(start_offset)) {
2229 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2230 << " Expected: " << start_offset
2231 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2232 return false;
2233 }
2234 if (!ReadDexFileHeader(file, oat_dex_file)) {
2235 return false;
2236 }
2237 if (extracted_size < oat_dex_file->dex_file_size_) {
2238 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2239 << " file size from header: " << oat_dex_file->dex_file_size_
2240 << " File: " << oat_dex_file->GetLocation();
2241 return false;
2242 }
2243
2244 // Override the checksum from header with the CRC from ZIP entry.
2245 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2246
2247 // Seek both file and stream to the end offset.
2248 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2249 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2250 if (actual_offset != static_cast<off_t>(end_offset)) {
2251 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2252 << " Expected: " << end_offset
2253 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2254 return false;
2255 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002256 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002257 if (actual_offset != static_cast<off_t>(end_offset)) {
2258 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2259 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2260 return false;
2261 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002262 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002263 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2264 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2265 return false;
2266 }
2267
2268 // If we extracted more than the size specified in the header, truncate the file.
2269 if (extracted_size > oat_dex_file->dex_file_size_) {
2270 if (file->SetLength(end_offset) != 0) {
2271 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002272 << " File: " << oat_dex_file->GetLocation()
2273 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002274 return false;
2275 }
2276 }
2277
2278 return true;
2279}
2280
David Brazdil7b49e6c2016-09-01 11:06:18 +01002281bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002282 File* file,
2283 OatDexFile* oat_dex_file,
2284 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002285 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2286 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002287
2288 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2289 if (input_offset != static_cast<off_t>(0)) {
2290 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2291 << " Expected: 0"
2292 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2293 return false;
2294 }
2295 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2296 return false;
2297 }
2298
2299 // Copy the input dex file using sendfile().
2300 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2301 PLOG(ERROR) << "Failed to copy dex file to oat file."
2302 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2303 return false;
2304 }
2305 if (file->Flush() != 0) {
2306 PLOG(ERROR) << "Failed to flush dex file."
2307 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2308 return false;
2309 }
2310
2311 // Check file position and seek the stream to the end offset.
2312 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2313 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2314 if (actual_offset != static_cast<off_t>(end_offset)) {
2315 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2316 << " Expected: " << end_offset
2317 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2318 return false;
2319 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002320 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002321 if (actual_offset != static_cast<off_t>(end_offset)) {
2322 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2323 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2324 return false;
2325 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002326 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002327 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2328 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2329 return false;
2330 }
2331
2332 return true;
2333}
2334
David Brazdil7b49e6c2016-09-01 11:06:18 +01002335bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002336 OatDexFile* oat_dex_file,
2337 const uint8_t* dex_file) {
2338 // Note: The raw data has already been checked to contain the header
2339 // and all the data that the header specifies as the file size.
2340 DCHECK(dex_file != nullptr);
2341 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2342 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2343
David Brazdil7b49e6c2016-09-01 11:06:18 +01002344 if (!out->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002346 << " to " << out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002347 return false;
2348 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002349 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002350 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2351 << " File: " << oat_dex_file->GetLocation();
2352 return false;
2353 }
2354
2355 // Update dex file size and resize class offsets in the OatDexFile.
2356 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2357 oat_dex_file->dex_file_size_ = header->file_size_;
2358 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2359 return true;
2360}
2361
2362bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2363 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2364
David Brazdil181e1cc2016-09-01 16:38:47 +00002365 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2366 if (initial_offset == static_cast<off_t>(-1)) {
2367 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2368 return false;
2369 }
2370
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002371 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2372 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2373 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2374 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2375 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2376 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2377 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2378 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2379 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2380 return false;
2381 }
2382
2383 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2384 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2385
2386 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2387 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2388
2389 // Write OatDexFile.
2390 if (!oat_dex_file->Write(this, rodata)) {
2391 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2392 return false;
2393 }
2394 }
2395
David Brazdil181e1cc2016-09-01 16:38:47 +00002396 // Seek back to the initial position.
2397 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2398 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2399 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2400 return false;
2401 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002402
David Brazdilb92ba622016-09-01 16:00:30 +00002403 return true;
2404}
2405
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002406bool OatWriter::OpenDexFiles(
2407 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002408 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002409 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2410 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2411 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2412
2413 if (oat_dex_files_.empty()) {
2414 // Nothing to do.
2415 return true;
2416 }
2417
2418 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002419 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2420
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002421 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002422 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2423 length,
2424 PROT_READ | PROT_WRITE,
2425 MAP_SHARED,
2426 file->Fd(),
2427 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2428 /* low_4gb */ false,
2429 file->GetPath().c_str(),
2430 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002431 if (dex_files_map == nullptr) {
2432 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2433 << " error: " << error_msg;
2434 return false;
2435 }
2436 std::vector<std::unique_ptr<const DexFile>> dex_files;
2437 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2438 // Make sure no one messed with input files while we were copying data.
2439 // At the very least we need consistent file size and number of class definitions.
2440 const uint8_t* raw_dex_file =
2441 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2442 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2443 // Note: ValidateDexFileHeader() already logged an error message.
2444 LOG(ERROR) << "Failed to verify written dex file header!"
2445 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2446 << " ~ " << static_cast<const void*>(raw_dex_file);
2447 return false;
2448 }
2449 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2450 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2451 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2452 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2453 << " Output: " << file->GetPath();
2454 return false;
2455 }
2456 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2457 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2458 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2459 << " Output: " << file->GetPath();
2460 return false;
2461 }
2462
2463 // Now, open the dex file.
2464 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2465 oat_dex_file.dex_file_size_,
2466 oat_dex_file.GetLocation(),
2467 oat_dex_file.dex_file_location_checksum_,
2468 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002469 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002470 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002471 &error_msg));
2472 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002473 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2474 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002475 return false;
2476 }
2477 }
2478
2479 *opened_dex_files_map = std::move(dex_files_map);
2480 *opened_dex_files = std::move(dex_files);
2481 return true;
2482}
2483
2484bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002485 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002486 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2487 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2488
David Brazdil7b49e6c2016-09-01 11:06:18 +01002489 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2490 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2491 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2492 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2493 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2494 return false;
2495 }
2496
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002497 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2498 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2499 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002500 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2501
2502 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2503 oat_dex_file->class_offsets_.empty()) {
2504 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002505 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002506
2507 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2508 if (table_size == 0u) {
2509 continue;
2510 }
2511
2512 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002513 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002514 const DexFile& dex_file = *opened_dex_files[i];
2515 {
2516 std::unique_ptr<TypeLookupTable> type_lookup_table =
2517 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2518 type_lookup_table_oat_dex_files_.push_back(
2519 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2520 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2521 }
2522 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002523
2524 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002525 size_t initial_offset = oat_size_;
2526 size_t rodata_offset = RoundUp(initial_offset, 4);
2527 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002528
2529 if (padding_size != 0u) {
2530 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002531 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002532 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2533 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002534 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002535 return false;
2536 }
2537 }
2538
2539 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002540 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002541 DCHECK_EQ(table_size, table->RawDataLength());
2542
David Brazdil7b49e6c2016-09-01 11:06:18 +01002543 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002544 PLOG(ERROR) << "Failed to write lookup table."
2545 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002546 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002547 return false;
2548 }
2549
2550 oat_dex_file->lookup_table_offset_ = rodata_offset;
2551
David Brazdil7b49e6c2016-09-01 11:06:18 +01002552 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002553 size_oat_lookup_table_ += table_size;
2554 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002555 }
2556
David Brazdil7b49e6c2016-09-01 11:06:18 +01002557 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002558 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002559 << " File: " << oat_rodata->GetLocation();
2560 return false;
2561 }
2562
2563 return true;
2564}
2565
2566bool OatWriter::WriteVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002567 if (!kIsVdexEnabled) {
2568 return true;
2569 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002570 off_t actual_offset = vdex_out->Seek(0, kSeekSet);
2571 if (actual_offset != 0) {
2572 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2573 << " File: " << vdex_out->GetLocation();
2574 return false;
2575 }
2576
David Brazdil5d5a36b2016-09-14 15:34:10 +01002577 DCHECK_NE(vdex_dex_files_offset_, 0u);
2578 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2579
2580 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002581 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2582 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002583
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002584 VdexFile::Header vdex_header(
2585 dex_section_size, verifier_deps_section_size, quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002586 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2587 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002588 return false;
2589 }
2590
David Brazdil5d5a36b2016-09-14 15:34:10 +01002591 if (!vdex_out->Flush()) {
2592 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2593 << " File: " << vdex_out->GetLocation();
2594 return false;
2595 }
2596
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002597 return true;
2598}
2599
Vladimir Markof4da6752014-08-01 19:04:18 +01002600bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2601 static const uint8_t kPadding[] = {
2602 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2603 };
2604 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002605 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002606 return false;
2607 }
2608 size_code_alignment_ += aligned_code_delta;
2609 return true;
2610}
2611
Vladimir Marko944da602016-02-19 12:27:55 +00002612void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2613 DCHECK(dex_files_ != nullptr);
2614 DCHECK(relative_patcher_ != nullptr);
2615 DCHECK_NE(oat_data_offset_, 0u);
2616 if (image_writer_ != nullptr && !dex_files_->empty()) {
2617 // The oat data begin may not be initialized yet but the oat file offset is ready.
2618 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2619 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2620 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002621 }
2622}
2623
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002624OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2625 DexFileSource source,
2626 CreateTypeLookupTable create_type_lookup_table)
2627 : source_(source),
2628 create_type_lookup_table_(create_type_lookup_table),
2629 dex_file_size_(0),
2630 offset_(0),
2631 dex_file_location_size_(strlen(dex_file_location)),
2632 dex_file_location_data_(dex_file_location),
2633 dex_file_location_checksum_(0u),
2634 dex_file_offset_(0u),
2635 class_offsets_offset_(0u),
2636 lookup_table_offset_(0u),
2637 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002638}
2639
2640size_t OatWriter::OatDexFile::SizeOf() const {
2641 return sizeof(dex_file_location_size_)
2642 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002643 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002644 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002645 + sizeof(class_offsets_offset_)
2646 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002647}
2648
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002649void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2650 DCHECK_EQ(class_offsets_offset_, 0u);
2651 if (!class_offsets_.empty()) {
2652 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002653 size_t initial_offset = oat_writer->oat_size_;
2654 size_t offset = RoundUp(initial_offset, 4);
2655 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002656 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002657 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002658 }
2659}
2660
2661bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2662 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002663 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002664
Vladimir Markoe079e212016-05-25 12:49:49 +01002665 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002666 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002667 return false;
2668 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002669 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002670
Vladimir Markoe079e212016-05-25 12:49:49 +01002671 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002672 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002673 return false;
2674 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002675 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002676
Vladimir Markoe079e212016-05-25 12:49:49 +01002677 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002678 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002679 return false;
2680 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002681 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002682
Vladimir Markoe079e212016-05-25 12:49:49 +01002683 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002684 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002685 return false;
2686 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002687 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002688
Vladimir Markoe079e212016-05-25 12:49:49 +01002689 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002690 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2691 return false;
2692 }
2693 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2694
Vladimir Markoe079e212016-05-25 12:49:49 +01002695 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002696 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2697 return false;
2698 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002699 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002700
2701 return true;
2702}
2703
2704bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002705 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002706 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2707 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002708 return false;
2709 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002710 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002711 return true;
2712}
2713
Brian Carlstromba150c32013-08-27 17:31:03 -07002714OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002715 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002716 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002717 mirror::Class::Status status)
2718 : compiled_methods_(compiled_methods) {
2719 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002720 CHECK_LE(num_non_null_compiled_methods, num_methods);
2721
Brian Carlstrom265091e2013-01-30 14:08:26 -08002722 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002723 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2724
2725 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2726 // apply when there are 0 methods, we just arbitrarily say that 0
2727 // methods means kOatClassNoneCompiled and that we won't use
2728 // kOatClassAllCompiled unless there is at least one compiled
2729 // method. This means in an interpretter only system, we can assert
2730 // that all classes are kOatClassNoneCompiled.
2731 if (num_non_null_compiled_methods == 0) {
2732 type_ = kOatClassNoneCompiled;
2733 } else if (num_non_null_compiled_methods == num_methods) {
2734 type_ = kOatClassAllCompiled;
2735 } else {
2736 type_ = kOatClassSomeCompiled;
2737 }
2738
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002739 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002740 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002741 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002742
2743 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2744 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002745 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002746 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2747 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2748 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2749 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002750 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002751 method_bitmap_size_ = 0;
2752 }
2753
2754 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002755 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002756 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002757 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2758 } else {
2759 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2760 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2761 if (type_ == kOatClassSomeCompiled) {
2762 method_bitmap_->SetBit(i);
2763 }
2764 }
2765 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002766}
2767
Brian Carlstrom265091e2013-01-30 14:08:26 -08002768size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2769 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002770 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2771 if (method_offset == 0) {
2772 return 0;
2773 }
2774 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002775}
2776
2777size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2778 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002779 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002780}
2781
2782size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002783 return sizeof(status_)
2784 + sizeof(type_)
2785 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2786 + method_bitmap_size_
2787 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002788}
2789
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002790bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002791 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002792 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002793 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002794 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002795 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002796 return false;
2797 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002798 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002799
Vladimir Markoe079e212016-05-25 12:49:49 +01002800 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002801 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002802 return false;
2803 }
2804 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002805
Brian Carlstromba150c32013-08-27 17:31:03 -07002806 if (method_bitmap_size_ != 0) {
2807 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002808 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002809 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002810 return false;
2811 }
2812 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002813
Vladimir Markoe079e212016-05-25 12:49:49 +01002814 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002815 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002816 return false;
2817 }
2818 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2819 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002820
Vladimir Markoe079e212016-05-25 12:49:49 +01002821 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002822 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002823 return false;
2824 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002825 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002826 return true;
2827}
2828
Brian Carlstrome24fa612011-09-29 00:53:55 -07002829} // namespace art