blob: afcdf5ea172c966d49c3a5e7c7492c4441dec6e4 [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:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800107 enum Type {
108 kNone,
109 kZipEntry,
110 kRawFile,
111 kRawData,
112 };
113
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000114 explicit DexFileSource(ZipEntry* zip_entry)
115 : type_(kZipEntry), source_(zip_entry) {
116 DCHECK(source_ != nullptr);
117 }
118
119 explicit DexFileSource(File* raw_file)
120 : type_(kRawFile), source_(raw_file) {
121 DCHECK(source_ != nullptr);
122 }
123
124 explicit DexFileSource(const uint8_t* dex_file)
125 : type_(kRawData), source_(dex_file) {
126 DCHECK(source_ != nullptr);
127 }
128
Mathieu Chartier497d5262017-02-28 20:17:30 -0800129 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000130 bool IsZipEntry() const { return type_ == kZipEntry; }
131 bool IsRawFile() const { return type_ == kRawFile; }
132 bool IsRawData() const { return type_ == kRawData; }
133
134 ZipEntry* GetZipEntry() const {
135 DCHECK(IsZipEntry());
136 DCHECK(source_ != nullptr);
137 return static_cast<ZipEntry*>(const_cast<void*>(source_));
138 }
139
140 File* GetRawFile() const {
141 DCHECK(IsRawFile());
142 DCHECK(source_ != nullptr);
143 return static_cast<File*>(const_cast<void*>(source_));
144 }
145
146 const uint8_t* GetRawData() const {
147 DCHECK(IsRawData());
148 DCHECK(source_ != nullptr);
149 return static_cast<const uint8_t*>(source_);
150 }
151
152 void Clear() {
153 type_ = kNone;
154 source_ = nullptr;
155 }
156
157 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000158 Type type_;
159 const void* source_;
160};
161
Vladimir Marko49b0f452015-12-10 13:49:19 +0000162class OatWriter::OatClass {
163 public:
164 OatClass(size_t offset,
165 const dchecked_vector<CompiledMethod*>& compiled_methods,
166 uint32_t num_non_null_compiled_methods,
167 mirror::Class::Status status);
168 OatClass(OatClass&& src) = default;
169 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
170 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
171 size_t SizeOf() const;
172 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
173
174 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
175 return compiled_methods_[class_def_method_index];
176 }
177
178 // Offset of start of OatClass from beginning of OatHeader. It is
179 // used to validate file position when writing.
180 size_t offset_;
181
182 // CompiledMethods for each class_def_method_index, or null if no method is available.
183 dchecked_vector<CompiledMethod*> compiled_methods_;
184
185 // Offset from OatClass::offset_ to the OatMethodOffsets for the
186 // class_def_method_index. If 0, it means the corresponding
187 // CompiledMethod entry in OatClass::compiled_methods_ should be
188 // null and that the OatClass::type_ should be kOatClassBitmap.
189 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
190
191 // Data to write.
192
193 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
194 int16_t status_;
195
196 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
197 uint16_t type_;
198
199 uint32_t method_bitmap_size_;
200
201 // bit vector indexed by ClassDef method index. When
202 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
203 // method has an OatMethodOffsets in methods_offsets_, otherwise
204 // the entry was ommited to save space. If OatClassType::type_ is
205 // not is kOatClassBitmap, the bitmap will be null.
206 std::unique_ptr<BitVector> method_bitmap_;
207
208 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
209 // present in the OatClass. Note that some may be missing if
210 // OatClass::compiled_methods_ contains null values (and
211 // oat_method_offsets_offsets_from_oat_class_ should contain 0
212 // values in this case).
213 dchecked_vector<OatMethodOffsets> method_offsets_;
214 dchecked_vector<OatQuickMethodHeader> method_headers_;
215
216 private:
217 size_t GetMethodOffsetsRawSize() const {
218 return method_offsets_.size() * sizeof(method_offsets_[0]);
219 }
220
221 DISALLOW_COPY_AND_ASSIGN(OatClass);
222};
223
224class OatWriter::OatDexFile {
225 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000226 OatDexFile(const char* dex_file_location,
227 DexFileSource source,
228 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000229 OatDexFile(OatDexFile&& src) = default;
230
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000231 const char* GetLocation() const {
232 return dex_file_location_data_;
233 }
234
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000235 void ReserveClassOffsets(OatWriter* oat_writer);
236
Vladimir Marko49b0f452015-12-10 13:49:19 +0000237 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000238 bool Write(OatWriter* oat_writer, OutputStream* out) const;
239 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
240
241 // The source of the dex file.
242 DexFileSource source_;
243
244 // Whether to create the type lookup table.
245 CreateTypeLookupTable create_type_lookup_table_;
246
247 // Dex file size. Initialized when writing the dex file.
248 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000249
250 // Offset of start of OatDexFile from beginning of OatHeader. It is
251 // used to validate file position when writing.
252 size_t offset_;
253
254 // Data to write.
255 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000256 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000257 uint32_t dex_file_location_checksum_;
258 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000259 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000260 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000261
262 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000263 dchecked_vector<uint32_t> class_offsets_;
264
265 private:
266 size_t GetClassOffsetsRawSize() const {
267 return class_offsets_.size() * sizeof(class_offsets_[0]);
268 }
269
270 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
271};
272
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100273#define DCHECK_OFFSET() \
274 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
275 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
276
277#define DCHECK_OFFSET_() \
278 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
279 << "file_offset=" << file_offset << " offset_=" << offset_
280
Jeff Hao608f2ce2016-10-19 11:17:11 -0700281OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000282 : write_state_(WriteState::kAddingDexFileSources),
283 timings_(timings),
284 raw_dex_files_(),
285 zip_archives_(),
286 zipped_dex_files_(),
287 zipped_dex_file_locations_(),
288 compiler_driver_(nullptr),
289 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800290 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000291 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100292 vdex_size_(0u),
293 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100294 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100295 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100296 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000297 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000298 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000299 bss_roots_offset_(0u),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000300 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000301 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100302 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700303 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100304 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000305 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700306 size_dex_file_alignment_(0),
307 size_executable_offset_alignment_(0),
308 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700309 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700310 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100311 size_verifier_deps_(0),
312 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100313 size_quickening_info_(0),
314 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700315 size_interpreter_to_interpreter_bridge_(0),
316 size_interpreter_to_compiled_code_bridge_(0),
317 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800318 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700319 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700320 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700321 size_quick_to_interpreter_bridge_(0),
322 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100323 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700324 size_code_(0),
325 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100326 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100327 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700328 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700329 size_oat_dex_file_location_size_(0),
330 size_oat_dex_file_location_data_(0),
331 size_oat_dex_file_location_checksum_(0),
332 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000333 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000334 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000335 size_oat_lookup_table_alignment_(0),
336 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000337 size_oat_class_offsets_alignment_(0),
338 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700339 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700340 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700341 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100342 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000343 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700344 absolute_patch_locations_(),
345 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000346}
347
348bool OatWriter::AddDexFileSource(const char* filename,
349 const char* location,
350 CreateTypeLookupTable create_type_lookup_table) {
351 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
352 uint32_t magic;
353 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700354 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
355 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000356 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
357 return false;
358 } else if (IsDexMagic(magic)) {
359 // The file is open for reading, not writing, so it's OK to let the File destructor
360 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700361 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000362 oat_dex_files_.emplace_back(location,
363 DexFileSource(raw_dex_files_.back().get()),
364 create_type_lookup_table);
365 } else if (IsZipMagic(magic)) {
366 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
367 return false;
368 }
369 } else {
370 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
371 return false;
372 }
373 return true;
374}
375
376// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700377bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000378 const char* location,
379 CreateTypeLookupTable create_type_lookup_table) {
380 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
381 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700382 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000383 ZipArchive* zip_archive = zip_archives_.back().get();
384 if (zip_archive == nullptr) {
385 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
386 << error_msg;
387 return false;
388 }
389 for (size_t i = 0; ; ++i) {
390 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
391 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
392 if (entry == nullptr) {
393 break;
394 }
395 zipped_dex_files_.push_back(std::move(entry));
396 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
397 const char* full_location = zipped_dex_file_locations_.back().c_str();
398 oat_dex_files_.emplace_back(full_location,
399 DexFileSource(zipped_dex_files_.back().get()),
400 create_type_lookup_table);
401 }
402 if (zipped_dex_file_locations_.empty()) {
403 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
404 return false;
405 }
406 return true;
407}
408
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000409// Add dex file source(s) from a vdex file specified by a file handle.
410bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
411 const char* location,
412 CreateTypeLookupTable create_type_lookup_table) {
413 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
414 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000415 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000416 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
417 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000418 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
419 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000420 }
421 if (!DexFile::IsMagicValid(current_dex_data)) {
422 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
423 return false;
424 }
425 // We used `zipped_dex_file_locations_` to keep the strings in memory.
426 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
427 const char* full_location = zipped_dex_file_locations_.back().c_str();
428 oat_dex_files_.emplace_back(full_location,
429 DexFileSource(current_dex_data),
430 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000431 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000432 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000433
434 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
435 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
436 return false;
437 }
438
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000439 if (oat_dex_files_.empty()) {
440 LOG(ERROR) << "No dex files in vdex file created from " << location;
441 return false;
442 }
443 return true;
444}
445
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000446// Add dex file source from raw memory.
447bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
448 const char* location,
449 uint32_t location_checksum,
450 CreateTypeLookupTable create_type_lookup_table) {
451 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
452 if (data.size() < sizeof(DexFile::Header)) {
453 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
454 << data.size() << " File: " << location;
455 return false;
456 }
457 if (!ValidateDexFileHeader(data.data(), location)) {
458 return false;
459 }
460 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
461 if (data.size() < header->file_size_) {
462 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
463 << " file size from header: " << header->file_size_ << " File: " << location;
464 return false;
465 }
466
467 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
468 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
469 return true;
470}
471
472dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
473 dchecked_vector<const char*> locations;
474 locations.reserve(oat_dex_files_.size());
475 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
476 locations.push_back(oat_dex_file.GetLocation());
477 }
478 return locations;
479}
480
481bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100482 File* vdex_file,
483 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000484 InstructionSet instruction_set,
485 const InstructionSetFeatures* instruction_set_features,
486 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800487 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000488 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
490 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
491 CHECK(write_state_ == WriteState::kAddingDexFileSources);
492
David Brazdil7b49e6c2016-09-01 11:06:18 +0100493 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
494 if (!RecordOatDataOffset(oat_rodata)) {
495 return false;
496 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497
498 std::unique_ptr<MemMap> dex_files_map;
499 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100500
501 // Initialize VDEX and OAT headers.
502 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000503 // Reserve space for Vdex header and checksums.
504 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100505 }
506 size_t oat_data_offset = InitOatHeader(instruction_set,
507 instruction_set_features,
508 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
509 key_value_store);
510 oat_size_ = InitOatDexFiles(oat_data_offset);
511
512 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
513
514 if (kIsVdexEnabled) {
515 std::unique_ptr<BufferedOutputStream> vdex_out(
516 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100517 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000518 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100519 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
520 return false;
521 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100522 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000523 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100524 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000525 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100526 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
527 return false;
528 }
529
530 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
531 // difficult because we're not using the OutputStream directly.
532 if (!oat_dex_files_.empty()) {
533 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
534 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
535 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000536 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000537
David Brazdil7b49e6c2016-09-01 11:06:18 +0100538 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000539 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
540 return false;
541 }
542
David Brazdil7b49e6c2016-09-01 11:06:18 +0100543 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000544 for (OatDexFile& oat_dex_file : oat_dex_files_) {
545 oat_dex_file.ReserveClassOffsets(this);
546 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100547
David Brazdil7b49e6c2016-09-01 11:06:18 +0100548 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000549 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
550 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000551 }
552
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000553 *opened_dex_files_map = std::move(dex_files_map);
554 *opened_dex_files = std::move(dex_files);
555 write_state_ = WriteState::kPrepareLayout;
556 return true;
557}
558
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100559void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000560 CHECK(write_state_ == WriteState::kPrepareLayout);
561
Vladimir Marko944da602016-02-19 12:27:55 +0000562 relative_patcher_ = relative_patcher;
563 SetMultiOatRelativePatcherAdjustment();
564
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000565 if (compiling_boot_image_) {
566 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800567 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100568 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000569 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100570
David Brazdil7b49e6c2016-09-01 11:06:18 +0100571 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800572 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000573 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800574 offset = InitOatClasses(offset);
575 }
576 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000577 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100578 offset = InitOatMaps(offset);
579 }
580 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000581 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800582 offset = InitOatCode(offset);
583 }
584 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000585 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800586 offset = InitOatCodeDexFiles(offset);
587 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100588 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700589
Vladimir Marko1998cd02017-01-13 13:02:58 +0000590 {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000591 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
592 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100593 }
594
Brian Carlstrome24fa612011-09-29 00:53:55 -0700595 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800596 if (compiling_boot_image_) {
597 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000598 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800599 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000600
601 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700602}
603
Ian Rogers0571d352011-11-03 19:51:38 -0700604OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700605}
606
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100607class OatWriter::DexMethodVisitor {
608 public:
609 DexMethodVisitor(OatWriter* writer, size_t offset)
610 : writer_(writer),
611 offset_(offset),
612 dex_file_(nullptr),
613 class_def_index_(DexFile::kDexNoIndex) {
614 }
615
616 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
617 DCHECK(dex_file_ == nullptr);
618 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
619 dex_file_ = dex_file;
620 class_def_index_ = class_def_index;
621 return true;
622 }
623
624 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
625
626 virtual bool EndClass() {
627 if (kIsDebugBuild) {
628 dex_file_ = nullptr;
629 class_def_index_ = DexFile::kDexNoIndex;
630 }
631 return true;
632 }
633
634 size_t GetOffset() const {
635 return offset_;
636 }
637
638 protected:
639 virtual ~DexMethodVisitor() { }
640
641 OatWriter* const writer_;
642
643 // The offset is usually advanced for each visited method by the derived class.
644 size_t offset_;
645
646 // The dex file and class def index are set in StartClass().
647 const DexFile* dex_file_;
648 size_t class_def_index_;
649};
650
651class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
652 public:
653 OatDexMethodVisitor(OatWriter* writer, size_t offset)
654 : DexMethodVisitor(writer, offset),
655 oat_class_index_(0u),
656 method_offsets_index_(0u) {
657 }
658
659 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
660 DexMethodVisitor::StartClass(dex_file, class_def_index);
661 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
662 method_offsets_index_ = 0u;
663 return true;
664 }
665
666 bool EndClass() {
667 ++oat_class_index_;
668 return DexMethodVisitor::EndClass();
669 }
670
671 protected:
672 size_t oat_class_index_;
673 size_t method_offsets_index_;
674};
675
676class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
677 public:
678 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
679 : DexMethodVisitor(writer, offset),
680 compiled_methods_(),
681 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000682 size_t num_classes = 0u;
683 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
684 num_classes += oat_dex_file.class_offsets_.size();
685 }
686 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687 compiled_methods_.reserve(256u);
688 }
689
690 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
691 DexMethodVisitor::StartClass(dex_file, class_def_index);
692 compiled_methods_.clear();
693 num_non_null_compiled_methods_ = 0u;
694 return true;
695 }
696
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300697 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
698 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100699 // Fill in the compiled_methods_ array for methods that have a
700 // CompiledMethod. We track the number of non-null entries in
701 // num_non_null_compiled_methods_ since we only want to allocate
702 // OatMethodOffsets for the compiled methods.
703 uint32_t method_idx = it.GetMemberIndex();
704 CompiledMethod* compiled_method =
705 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
706 compiled_methods_.push_back(compiled_method);
707 if (compiled_method != nullptr) {
708 ++num_non_null_compiled_methods_;
709 }
710 return true;
711 }
712
713 bool EndClass() {
714 ClassReference class_ref(dex_file_, class_def_index_);
715 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
716 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700717 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 status = compiled_class->GetStatus();
719 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000720 // The oat class status is used only for verification of resolved classes,
721 // so use kStatusErrorResolved whether the class was resolved or unresolved
722 // during compile-time verification.
723 status = mirror::Class::kStatusErrorResolved;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100724 } else {
725 status = mirror::Class::kStatusNotReady;
726 }
727
Vladimir Marko49b0f452015-12-10 13:49:19 +0000728 writer_->oat_classes_.emplace_back(offset_,
729 compiled_methods_,
730 num_non_null_compiled_methods_,
731 status);
732 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100733 return DexMethodVisitor::EndClass();
734 }
735
736 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000737 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100738 size_t num_non_null_compiled_methods_;
739};
740
741class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
742 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100743 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100744 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100745 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
746 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100747 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100748 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
749 }
750
751 bool EndClass() {
752 OatDexMethodVisitor::EndClass();
753 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100754 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100755 }
756 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100757 }
758
759 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700760 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000761 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
763
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100764 if (it.GetMethodCodeItem() != nullptr) {
765 current_quickening_info_offset_ += sizeof(uint32_t);
766 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100767 if (compiled_method != nullptr) {
768 // Derived from CompiledMethod.
769 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100770
Vladimir Marko35831e82015-09-11 11:59:18 +0100771 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
772 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800773 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800774
David Srbecky009e2a62015-04-15 02:46:30 +0100775 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100776 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800777 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000778 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000779 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
780 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800781 // Duplicate methods, we want the same code for both of them so that the oat writer puts
782 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800783 } else {
784 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100785 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800786 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000787 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100788 quick_code_offset = dedupe_map_.GetOrCreate(
789 compiled_method,
790 [this, &deduped, compiled_method, &it, thumb_offset]() {
791 deduped = false;
792 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
793 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800794 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100795
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100796 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000797 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100798 // TODO: Should this be a hard failure?
799 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700800 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000801 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
802 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100803 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000804 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100805 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800806 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100807
Elliott Hughes956af0f2014-12-11 14:34:28 -0800808 // Update quick method header.
809 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
810 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700811 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800812 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
813 // to 0-offset and we need to adjust it by code_offset.
814 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100815 if (!compiled_method->GetQuickCode().empty()) {
816 // If the code is compiled, we write the offset of the stack map relative
817 // to the code,
818 if (vmap_table_offset != 0u) {
819 vmap_table_offset += code_offset;
820 DCHECK_LT(vmap_table_offset, code_offset);
821 }
822 } else {
823 if (kIsVdexEnabled) {
824 // We write the offset in the .vdex file.
825 DCHECK_EQ(vmap_table_offset, 0u);
826 vmap_table_offset = current_quickening_info_offset_;
827 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
828 current_quickening_info_offset_ += map.size() * sizeof(map.front());
829 } else {
830 // We write the offset of the quickening info relative to the code.
831 vmap_table_offset += code_offset;
832 DCHECK_LT(vmap_table_offset, code_offset);
833 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800834 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800835 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
836 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
837 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100838 *method_header = OatQuickMethodHeader(vmap_table_offset,
839 frame_size_in_bytes,
840 core_spill_mask,
841 fp_spill_mask,
842 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100843
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000844 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800845 // Update offsets. (Checksum is updated when writing.)
846 offset_ += sizeof(*method_header); // Method header is prepended before code.
847 offset_ += code_size;
848 // Record absolute patch locations.
849 if (!compiled_method->GetPatches().empty()) {
850 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
851 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000852 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100853 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100854 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000855 if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
856 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
857 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
858 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000859 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
860 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
861 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
862 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100863 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100864 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800865 }
Alex Light78382fa2014-06-06 15:45:32 -0700866
David Srbecky91cc06c2016-03-07 16:13:58 +0000867 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000868 // Exclude quickened dex methods (code_size == 0) since they have no native code.
869 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
870 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800871 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000872 debug::MethodDebugInfo info = debug::MethodDebugInfo();
873 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000874 info.dex_file = dex_file_;
875 info.class_def_index = class_def_index_;
876 info.dex_method_index = it.GetMemberIndex();
877 info.access_flags = it.GetMethodAccessFlags();
878 info.code_item = it.GetMethodCodeItem();
879 info.isa = compiled_method->GetInstructionSet();
880 info.deduped = deduped;
881 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
882 info.is_optimized = method_header->IsOptimized();
883 info.is_code_address_text_relative = true;
884 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
885 info.code_size = code_size;
886 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
887 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
888 info.cfi = compiled_method->GetCFIInfo();
889 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100890 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100891
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100892 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
893 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
894 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100895 ++method_offsets_index_;
896 }
897
898 return true;
899 }
900
901 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000902 struct CodeOffsetsKeyComparator {
903 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100904 // Code is deduplicated by CompilerDriver, compare only data pointers.
905 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
906 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000907 }
908 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100909 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
910 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000911 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100912 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
913 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000914 }
915 return false;
916 }
917 };
918
David Srbecky009e2a62015-04-15 02:46:30 +0100919 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
920 const ClassDataItemIterator& it,
921 uint32_t thumb_offset) {
922 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100923 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100924 offset_ += CodeAlignmentSize(offset_, *compiled_method);
925 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100926 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
927 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
928 }
929
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100930 // Deduplication is already done on a pointer basis by the compiler driver,
931 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100932 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100933
David Srbecky009e2a62015-04-15 02:46:30 +0100934 // Cache of compiler's --debuggable option.
935 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100936
937 // Offset in the vdex file for the quickening info.
938 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939};
940
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
942 public:
943 InitMapMethodVisitor(OatWriter* writer, size_t offset)
944 : OatDexMethodVisitor(writer, offset) {
945 }
946
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700947 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700948 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000949 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100950 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
951
952 if (compiled_method != nullptr) {
953 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100954 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
955 // be in the vdex file.
956 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700957 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100958
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100959 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
960 uint32_t map_size = map.size() * sizeof(map[0]);
961 if (map_size != 0u) {
962 size_t offset = dedupe_map_.GetOrCreate(
963 map.data(),
964 [this, map_size]() {
965 uint32_t new_offset = offset_;
966 offset_ += map_size;
967 return new_offset;
968 });
969 // Code offset is not initialized yet, so set the map offset to 0u-offset.
970 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700971 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100972 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100973 }
974 ++method_offsets_index_;
975 }
976
977 return true;
978 }
979
980 private:
981 // Deduplication is already done on a pointer basis by the compiler driver,
982 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100983 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100984};
985
986class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
987 public:
988 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800989 : OatDexMethodVisitor(writer, offset),
990 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100991 }
992
993 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700994 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800995 const DexFile::TypeId& type_id =
996 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
997 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
998 // Skip methods that are not in the image.
999 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
1000 return true;
1001 }
1002
Vladimir Marko49b0f452015-12-10 13:49:19 +00001003 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001004 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1005
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001006 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001007 if (compiled_method != nullptr) {
1008 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1009 offsets = oat_class->method_offsets_[method_offsets_index_];
1010 ++method_offsets_index_;
1011 }
1012
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001013 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001014 // Unchecked as we hold mutator_lock_ on entry.
1015 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001016 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001017 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
1018 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001019 ArtMethod* method;
1020 if (writer_->HasBootImage()) {
1021 const InvokeType invoke_type = it.GetMethodInvokeType(
1022 dex_file_->GetClassDef(class_def_index_));
1023 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1024 *dex_file_,
1025 it.GetMemberIndex(),
1026 dex_cache,
1027 ScopedNullHandle<mirror::ClassLoader>(),
1028 nullptr,
1029 invoke_type);
1030 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001031 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001032 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001033 soa.Self()->AssertPendingException();
1034 mirror::Throwable* exc = soa.Self()->GetException();
1035 std::string dump = exc->Dump();
1036 LOG(FATAL) << dump;
1037 UNREACHABLE();
1038 }
1039 } else {
1040 // Should already have been resolved by the compiler, just peek into the dex cache.
1041 // It may not be resolved if the class failed to verify, in this case, don't set the
1042 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1043 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001044 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001045 if (method != nullptr &&
1046 compiled_method != nullptr &&
1047 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001048 method->SetEntryPointFromQuickCompiledCodePtrSize(
1049 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1050 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001051
1052 return true;
1053 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001054
1055 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001056 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001057};
1058
1059class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1060 public:
1061 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001062 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001063 : OatDexMethodVisitor(writer, relative_offset),
Vladimir Markobfb80d22017-02-14 14:08:12 +00001064 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001065 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001066 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001067 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001068 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001069 class_linker_(Runtime::Current()->GetClassLinker()),
1070 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001071 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001072 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001073 // If we're creating the image, the address space must be ready so that we can apply patches.
1074 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001075 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001076 }
1077
Vladimir Markof4da6752014-08-01 19:04:18 +01001078 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001079 }
1080
1081 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001082 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001083 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1084 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001085 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001086 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001087 }
1088 return true;
1089 }
1090
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001091 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001092 bool result = OatDexMethodVisitor::EndClass();
1093 if (oat_class_index_ == writer_->oat_classes_.size()) {
1094 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001095 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001096 if (UNLIKELY(offset_ == 0u)) {
1097 PLOG(ERROR) << "Failed to write final relative call thunks";
1098 result = false;
1099 }
1100 }
1101 return result;
1102 }
1103
1104 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001105 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001106 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001107 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1108
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001109 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001110 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001111 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001112 size_t file_offset = file_offset_;
1113 OutputStream* out = out_;
1114
Vladimir Marko35831e82015-09-11 11:59:18 +01001115 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1116 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001117
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001118 // Deduplicate code arrays.
1119 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1120 if (method_offsets.code_offset_ > offset_) {
1121 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1122 if (offset_ == 0u) {
1123 ReportWriteFailure("relative call thunk", it);
1124 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001125 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001126 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1127 if (alignment_size != 0) {
1128 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001129 ReportWriteFailure("code alignment padding", it);
1130 return false;
1131 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001132 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001133 DCHECK_OFFSET_();
1134 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001135 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001136 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1137 DCHECK_EQ(method_offsets.code_offset_,
1138 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001139 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001140 const OatQuickMethodHeader& method_header =
1141 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001142 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001143 ReportWriteFailure("method header", it);
1144 return false;
1145 }
1146 writer_->size_method_header_ += sizeof(method_header);
1147 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001148 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001149
1150 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001151 patched_code_.assign(quick_code.begin(), quick_code.end());
1152 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001153 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001154 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001155 switch (patch.GetType()) {
1156 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001157 // NOTE: Relative calls across oat files are not supported.
1158 uint32_t target_offset = GetTargetOffset(patch);
1159 writer_->relative_patcher_->PatchCall(&patched_code_,
1160 literal_offset,
1161 offset_ + literal_offset,
1162 target_offset);
1163 break;
1164 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001165 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001166 uint32_t target_offset = GetDexCacheOffset(patch);
1167 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1168 patch,
1169 offset_ + literal_offset,
1170 target_offset);
1171 break;
1172 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001173 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001174 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1175 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1176 patch,
1177 offset_ + literal_offset,
1178 target_offset);
1179 break;
1180 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001181 case LinkerPatch::Type::kStringBssEntry: {
1182 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1183 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1184 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1185 patch,
1186 offset_ + literal_offset,
1187 target_offset);
1188 break;
1189 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001190 case LinkerPatch::Type::kTypeRelative: {
1191 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1192 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1193 patch,
1194 offset_ + literal_offset,
1195 target_offset);
1196 break;
1197 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001198 case LinkerPatch::Type::kTypeBssEntry: {
1199 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1200 uint32_t target_offset = writer_->bss_type_entries_.Get(ref);
1201 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1202 patch,
1203 offset_ + literal_offset,
1204 target_offset);
1205 break;
1206 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001207 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001208 uint32_t target_offset = GetTargetOffset(patch);
1209 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1210 break;
1211 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001212 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001213 ArtMethod* method = GetTargetMethod(patch);
1214 PatchMethodAddress(&patched_code_, literal_offset, method);
1215 break;
1216 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001217 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001218 mirror::String* string = GetTargetString(patch);
1219 PatchObjectAddress(&patched_code_, literal_offset, string);
1220 break;
1221 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001222 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001223 mirror::Class* type = GetTargetType(patch);
1224 PatchObjectAddress(&patched_code_, literal_offset, type);
1225 break;
1226 }
1227 default: {
Richard Uhlerc52f3032017-03-02 13:45:45 +00001228 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001229 break;
1230 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001231 }
1232 }
1233 }
1234
Vladimir Markoe079e212016-05-25 12:49:49 +01001235 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001236 ReportWriteFailure("method code", it);
1237 return false;
1238 }
1239 writer_->size_code_ += code_size;
1240 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001241 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001242 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001243 ++method_offsets_index_;
1244 }
1245
1246 return true;
1247 }
1248
1249 private:
Vladimir Markobfb80d22017-02-14 14:08:12 +00001250 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001251 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001252 const size_t file_offset_;
1253 const ScopedObjectAccess soa_;
1254 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001255 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001256 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001257 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001258
1259 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1260 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001261 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001262 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001263
Mathieu Chartiere401d142015-04-22 13:56:20 -07001264 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001265 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001266 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001267 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001268 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1269 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001270 ArtMethod* method = dex_cache->GetResolvedMethod(
1271 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001272 CHECK(method != nullptr);
1273 return method;
1274 }
1275
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001276 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001277 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1278 // If there's no new compiled code, either we're compiling an app and the target method
1279 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001280 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001281 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001282 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001283 PointerSize size =
1284 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001285 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1286 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001287 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001288 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1289 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1290 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1291 target_offset = PointerToLowMemUInt32(oat_code_offset);
1292 } else {
1293 target_offset = target->IsNative()
1294 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1295 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1296 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001297 }
1298 return target_offset;
1299 }
1300
Vladimir Markocd556b02017-02-03 11:47:34 +00001301 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001302 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001303 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001304 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001305 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1306 }
1307
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001308 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobfb80d22017-02-14 14:08:12 +00001309 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001310 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markobfb80d22017-02-14 14:08:12 +00001311 ObjPtr<mirror::Class> type =
1312 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001313 CHECK(type != nullptr);
Vladimir Markobfb80d22017-02-14 14:08:12 +00001314 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001315 }
1316
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001317 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001318 ScopedObjectAccessUnchecked soa(Thread::Current());
1319 StackHandleScope<1> hs(soa.Self());
1320 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1321 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1322 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1323 patch.TargetStringIndex(),
1324 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001325 DCHECK(string != nullptr);
1326 DCHECK(writer_->HasBootImage() ||
1327 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1328 return string;
1329 }
1330
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001331 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001332 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001333 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1334 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1335 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1336 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001337 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001338 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001339 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1340 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001341 }
1342 }
1343
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001344 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001345 DCHECK(writer_->HasBootImage());
1346 object = writer_->image_writer_->GetImageAddress(object);
1347 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1348 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1349 // TODO: Clean up offset types. The target offset must be treated as signed.
1350 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1351 }
1352
Vladimir Markof4da6752014-08-01 19:04:18 +01001353 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001354 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001355 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001356 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001357 } else {
1358 // NOTE: We're using linker patches for app->boot references when the image can
1359 // be relocated and therefore we need to emit .oat_patches. We're not using this
1360 // for app->app references, so check that the object is in the image space.
1361 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001362 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001363 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001364 uint32_t address = PointerToLowMemUInt32(object);
1365 DCHECK_LE(offset + 4, code->size());
1366 uint8_t* data = &(*code)[offset];
1367 data[0] = address & 0xffu;
1368 data[1] = (address >> 8) & 0xffu;
1369 data[2] = (address >> 16) & 0xffu;
1370 data[3] = (address >> 24) & 0xffu;
1371 }
1372
Mathieu Chartiere401d142015-04-22 13:56:20 -07001373 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001374 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001375 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001376 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001377 } else if (kIsDebugBuild) {
1378 // NOTE: We're using linker patches for app->boot references when the image can
1379 // be relocated and therefore we need to emit .oat_patches. We're not using this
1380 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001381 std::vector<gc::space::ImageSpace*> image_spaces =
1382 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1383 bool contains_method = false;
1384 for (gc::space::ImageSpace* image_space : image_spaces) {
1385 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1386 contains_method |=
1387 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1388 }
1389 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001390 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001391 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001392 uint32_t address = PointerToLowMemUInt32(method);
1393 DCHECK_LE(offset + 4, code->size());
1394 uint8_t* data = &(*code)[offset];
1395 data[0] = address & 0xffu;
1396 data[1] = (address >> 8) & 0xffu;
1397 data[2] = (address >> 16) & 0xffu;
1398 data[3] = (address >> 24) & 0xffu;
1399 }
1400
Vladimir Markof4da6752014-08-01 19:04:18 +01001401 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001402 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001403 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001404 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001405 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1406 // TODO: Clean up offset types.
1407 // The target_offset must be treated as signed for cross-oat patching.
1408 const void* target = reinterpret_cast<const void*>(
1409 writer_->image_writer_->GetOatDataBegin(oat_index) +
1410 static_cast<int32_t>(target_offset));
1411 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001412 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001413 DCHECK_LE(offset + 4, code->size());
1414 uint8_t* data = &(*code)[offset];
1415 data[0] = address & 0xffu;
1416 data[1] = (address >> 8) & 0xffu;
1417 data[2] = (address >> 16) & 0xffu;
1418 data[3] = (address >> 24) & 0xffu;
1419 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420};
1421
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001422class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1423 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001424 WriteMapMethodVisitor(OatWriter* writer,
1425 OutputStream* out,
1426 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001427 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001428 : OatDexMethodVisitor(writer, relative_offset),
1429 out_(out),
1430 file_offset_(file_offset) {
1431 }
1432
1433 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001434 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001435 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1436
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001437 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001438 size_t file_offset = file_offset_;
1439 OutputStream* out = out_;
1440
Mingyao Yang063fc772016-08-02 11:02:54 -07001441 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001442 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001443 ++method_offsets_index_;
1444
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001445 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1446 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1447 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001448 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001449
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001450 // If vdex is enabled, only emit the map for compiled code. The quickening info
1451 // is emitted in the vdex already.
1452 if (map_offset != 0u &&
1453 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001454 // Transform map_offset to actual oat data offset.
1455 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1456 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001457 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001458
1459 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1460 size_t map_size = map.size() * sizeof(map[0]);
1461 if (map_offset == offset_) {
1462 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001463 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001464 ReportWriteFailure(it);
1465 return false;
1466 }
1467 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001469 }
1470 DCHECK_OFFSET_();
1471 }
1472
1473 return true;
1474 }
1475
1476 private:
1477 OutputStream* const out_;
1478 size_t const file_offset_;
1479
1480 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001481 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001482 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001483 }
1484};
1485
1486// Visit all methods from all classes in all dex files with the specified visitor.
1487bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1488 for (const DexFile* dex_file : *dex_files_) {
1489 const size_t class_def_count = dex_file->NumClassDefs();
1490 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1491 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1492 return false;
1493 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001494 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1495 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1496 const uint8_t* class_data = dex_file->GetClassData(class_def);
1497 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1498 ClassDataItemIterator it(*dex_file, class_data);
1499 while (it.HasNextStaticField()) {
1500 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001501 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001502 while (it.HasNextInstanceField()) {
1503 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001504 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001505 size_t class_def_method_index = 0u;
1506 while (it.HasNextDirectMethod()) {
1507 if (!visitor->VisitMethod(class_def_method_index, it)) {
1508 return false;
1509 }
1510 ++class_def_method_index;
1511 it.Next();
1512 }
1513 while (it.HasNextVirtualMethod()) {
1514 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1515 return false;
1516 }
1517 ++class_def_method_index;
1518 it.Next();
1519 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001520 }
1521 }
1522 if (UNLIKELY(!visitor->EndClass())) {
1523 return false;
1524 }
1525 }
1526 }
1527 return true;
1528}
1529
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001530size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1531 const InstructionSetFeatures* instruction_set_features,
1532 uint32_t num_dex_files,
1533 SafeMap<std::string, std::string>* key_value_store) {
1534 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1535 oat_header_.reset(OatHeader::Create(instruction_set,
1536 instruction_set_features,
1537 num_dex_files,
1538 key_value_store));
1539 size_oat_header_ += sizeof(OatHeader);
1540 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001541 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001542}
1543
1544size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001545 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1546 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001547 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001548 oat_dex_file.offset_ = offset;
1549 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001550 }
1551 return offset;
1552}
1553
Brian Carlstrom389efb02012-01-11 12:06:26 -08001554size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001555 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001556 InitOatClassesMethodVisitor visitor(this, offset);
1557 bool success = VisitDexMethods(&visitor);
1558 CHECK(success);
1559 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001560
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001561 // Update oat_dex_files_.
1562 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001563 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1564 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001565 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001566 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001567 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001568 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001569 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001570 CHECK(oat_class_it == oat_classes_.end());
1571
1572 return offset;
1573}
1574
1575size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001576 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1577 return offset;
1578 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001579 InitMapMethodVisitor visitor(this, offset);
1580 bool success = VisitDexMethods(&visitor);
1581 DCHECK(success);
1582 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001583
Brian Carlstrome24fa612011-09-29 00:53:55 -07001584 return offset;
1585}
1586
1587size_t OatWriter::InitOatCode(size_t offset) {
1588 // calculate the offsets within OatHeader to executable code
1589 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001590 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001591 // required to be on a new page boundary
1592 offset = RoundUp(offset, kPageSize);
1593 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001594 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001595 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001596 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001597
Ian Rogers848871b2013-08-05 10:56:33 -07001598 #define DO_TRAMPOLINE(field, fn_name) \
1599 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001600 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1601 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001602 (field) = compiler_driver_->Create ## fn_name(); \
1603 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001604
Ian Rogers848871b2013-08-05 10:56:33 -07001605 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001606 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001607 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001608 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1609 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001610
Ian Rogers848871b2013-08-05 10:56:33 -07001611 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001612 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001613 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1614 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1615 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001616 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001617 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001618 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001619 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001620 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001621 return offset;
1622}
1623
1624size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001625 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1626 return offset;
1627 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001628 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1629 bool success = VisitDexMethods(&code_visitor);
1630 DCHECK(success);
1631 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001632
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001633 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001634 InitImageMethodVisitor image_visitor(this, offset);
1635 success = VisitDexMethods(&image_visitor);
1636 DCHECK(success);
1637 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001638 }
Logan Chien8b977d32012-02-21 19:14:55 +08001639
Brian Carlstrome24fa612011-09-29 00:53:55 -07001640 return offset;
1641}
1642
Vladimir Markoaad75c62016-10-03 08:46:48 +00001643void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001644 if (HasBootImage()) {
1645 DCHECK(bss_string_entries_.empty());
1646 if (bss_type_entries_.empty()) {
1647 // Nothing to put to the .bss section.
1648 return;
1649 }
1650 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001651
1652 // Allocate space for app dex cache arrays in the .bss section.
1653 bss_start_ = RoundUp(oat_size_, kPageSize);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001654 bss_size_ = 0u;
Vladimir Marko1998cd02017-01-13 13:02:58 +00001655 if (!HasBootImage()) {
1656 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1657 for (const DexFile* dex_file : *dex_files_) {
1658 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1659 DexCacheArraysLayout layout(pointer_size, dex_file);
1660 bss_size_ += layout.Size();
1661 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001662 }
1663
1664 bss_roots_offset_ = bss_size_;
1665
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001666 // Prepare offsets for .bss Class entries.
1667 for (auto& entry : bss_type_entries_) {
1668 DCHECK_EQ(entry.second, 0u);
1669 entry.second = bss_start_ + bss_size_;
1670 bss_size_ += sizeof(GcRoot<mirror::Class>);
1671 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001672 // Prepare offsets for .bss String entries.
1673 for (auto& entry : bss_string_entries_) {
1674 DCHECK_EQ(entry.second, 0u);
1675 entry.second = bss_start_ + bss_size_;
1676 bss_size_ += sizeof(GcRoot<mirror::String>);
1677 }
1678}
1679
David Srbeckybc90fd02015-04-22 19:40:27 +01001680bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001681 CHECK(write_state_ == WriteState::kWriteRoData);
1682
Vladimir Markoe079e212016-05-25 12:49:49 +01001683 // Wrap out to update checksum with each write.
1684 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1685 out = &checksum_updating_out;
1686
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001687 if (!WriteClassOffsets(out)) {
1688 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001689 return false;
1690 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001691
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001692 if (!WriteClasses(out)) {
1693 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001694 return false;
1695 }
1696
Vladimir Markof4da6752014-08-01 19:04:18 +01001697 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001698 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001699 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001700 return false;
1701 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001702 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001703 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001704 relative_offset = WriteMaps(out, file_offset, relative_offset);
1705 if (relative_offset == 0) {
1706 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1707 return false;
1708 }
1709
David Srbeckybc90fd02015-04-22 19:40:27 +01001710 // Write padding.
1711 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1712 relative_offset += size_executable_offset_alignment_;
1713 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1714 size_t expected_file_offset = file_offset + relative_offset;
1715 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1716 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1717 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1718 return 0;
1719 }
1720 DCHECK_OFFSET();
1721
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001722 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001723 return true;
1724}
1725
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001726class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1727 public:
1728 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1729 : DexMethodVisitor(writer, offset),
1730 out_(out),
1731 written_bytes_(0u) {}
1732
1733 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1734 const ClassDataItemIterator& it) {
1735 if (it.GetMethodCodeItem() == nullptr) {
1736 // No CodeItem. Native or abstract method.
1737 return true;
1738 }
1739
1740 uint32_t method_idx = it.GetMemberIndex();
1741 CompiledMethod* compiled_method =
1742 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1743
1744 uint32_t length = 0;
1745 const uint8_t* data = nullptr;
1746 // VMap only contains quickening info if this method is not compiled.
1747 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1748 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1749 data = map.data();
1750 length = map.size() * sizeof(map.front());
1751 }
1752
1753 if (!out_->WriteFully(&length, sizeof(length)) ||
1754 !out_->WriteFully(data, length)) {
1755 PLOG(ERROR) << "Failed to write quickening info for "
1756 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1757 return false;
1758 }
1759 offset_ += sizeof(length) + length;
1760 written_bytes_ += sizeof(length) + length;
1761 return true;
1762 }
1763
1764 size_t GetNumberOfWrittenBytes() const {
1765 return written_bytes_;
1766 }
1767
1768 private:
1769 OutputStream* const out_;
1770 size_t written_bytes_;
1771};
1772
1773bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1774 if (!kIsVdexEnabled) {
1775 return true;
1776 }
1777
1778 size_t initial_offset = vdex_size_;
1779 size_t start_offset = RoundUp(initial_offset, 4u);
1780
1781 vdex_size_ = start_offset;
1782 vdex_quickening_info_offset_ = vdex_size_;
1783 size_quickening_info_alignment_ = start_offset - initial_offset;
1784
1785 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1786 if (actual_offset != static_cast<off_t>(start_offset)) {
1787 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1788 << " Expected: " << start_offset
1789 << " Output: " << vdex_out->GetLocation();
1790 return false;
1791 }
1792
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001793 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1794 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1795 if (!VisitDexMethods(&visitor)) {
1796 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1797 return false;
1798 }
1799
1800 if (!vdex_out->Flush()) {
1801 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1802 << " File: " << vdex_out->GetLocation();
1803 return false;
1804 }
1805 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1806 } else {
1807 // We know we did not quicken.
1808 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001809 }
1810
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001811 vdex_size_ += size_quickening_info_;
1812 return true;
1813}
1814
David Brazdil5d5a36b2016-09-14 15:34:10 +01001815bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1816 if (!kIsVdexEnabled) {
1817 return true;
1818 }
1819
1820 if (verifier_deps == nullptr) {
1821 // Nothing to write. Record the offset, but no need
1822 // for alignment.
1823 vdex_verifier_deps_offset_ = vdex_size_;
1824 return true;
1825 }
1826
1827 size_t initial_offset = vdex_size_;
1828 size_t start_offset = RoundUp(initial_offset, 4u);
1829
1830 vdex_size_ = start_offset;
1831 vdex_verifier_deps_offset_ = vdex_size_;
1832 size_verifier_deps_alignment_ = start_offset - initial_offset;
1833
1834 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1835 if (actual_offset != static_cast<off_t>(start_offset)) {
1836 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1837 << " Expected: " << start_offset
1838 << " Output: " << vdex_out->GetLocation();
1839 return false;
1840 }
1841
1842 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001843 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001844
1845 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1846 PLOG(ERROR) << "Failed to write verifier deps."
1847 << " File: " << vdex_out->GetLocation();
1848 return false;
1849 }
1850 if (!vdex_out->Flush()) {
1851 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1852 << " File: " << vdex_out->GetLocation();
1853 return false;
1854 }
1855
1856 size_verifier_deps_ = buffer.size();
1857 vdex_size_ += size_verifier_deps_;
1858 return true;
1859}
1860
David Srbeckybc90fd02015-04-22 19:40:27 +01001861bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001862 CHECK(write_state_ == WriteState::kWriteText);
1863
Vladimir Markoe079e212016-05-25 12:49:49 +01001864 // Wrap out to update checksum with each write.
1865 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1866 out = &checksum_updating_out;
1867
Vladimir Marko944da602016-02-19 12:27:55 +00001868 SetMultiOatRelativePatcherAdjustment();
1869
David Srbeckybc90fd02015-04-22 19:40:27 +01001870 const size_t file_offset = oat_data_offset_;
1871 size_t relative_offset = oat_header_->GetExecutableOffset();
1872 DCHECK_OFFSET();
1873
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001874 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001875 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001876 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001877 return false;
1878 }
1879
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001880 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1881 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001882 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001883 return false;
1884 }
1885
Vladimir Markof4da6752014-08-01 19:04:18 +01001886 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001887 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001888 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1889 return false;
1890 }
1891
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001892 if (kIsDebugBuild) {
1893 uint32_t size_total = 0;
1894 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001895 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1896 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001897
David Brazdil7b49e6c2016-09-01 11:06:18 +01001898 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001899 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001900 DO_STAT(size_dex_file_alignment_);
1901 DO_STAT(size_executable_offset_alignment_);
1902 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001903 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001904 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001905 DO_STAT(size_verifier_deps_);
1906 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001907 DO_STAT(size_quickening_info_);
1908 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001909 DO_STAT(size_interpreter_to_interpreter_bridge_);
1910 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1911 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001912 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001913 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001914 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001915 DO_STAT(size_quick_to_interpreter_bridge_);
1916 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001917 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001918 DO_STAT(size_code_);
1919 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001920 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001921 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001922 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001923 DO_STAT(size_oat_dex_file_location_size_);
1924 DO_STAT(size_oat_dex_file_location_data_);
1925 DO_STAT(size_oat_dex_file_location_checksum_);
1926 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001927 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001928 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001929 DO_STAT(size_oat_lookup_table_alignment_);
1930 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001931 DO_STAT(size_oat_class_offsets_alignment_);
1932 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001933 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001934 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001935 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001936 DO_STAT(size_oat_class_method_offsets_);
1937 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001938
David Brazdil7b49e6c2016-09-01 11:06:18 +01001939 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1940
1941 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1942 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001943 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001944
David Brazdil7b49e6c2016-09-01 11:06:18 +01001945 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1946 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001947
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001948 write_state_ = WriteState::kWriteHeader;
1949 return true;
1950}
1951
1952bool OatWriter::WriteHeader(OutputStream* out,
1953 uint32_t image_file_location_oat_checksum,
1954 uintptr_t image_file_location_oat_begin,
1955 int32_t image_patch_delta) {
1956 CHECK(write_state_ == WriteState::kWriteHeader);
1957
1958 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1959 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001960 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001961 CHECK_EQ(image_patch_delta, 0);
1962 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1963 } else {
1964 CHECK_ALIGNED(image_patch_delta, kPageSize);
1965 oat_header_->SetImagePatchDelta(image_patch_delta);
1966 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001967 oat_header_->UpdateChecksumWithHeaderData();
1968
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001969 const size_t file_offset = oat_data_offset_;
1970
1971 off_t current_offset = out->Seek(0, kSeekCurrent);
1972 if (current_offset == static_cast<off_t>(-1)) {
1973 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1974 return false;
1975 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001976 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001977 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1978 return false;
1979 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001980 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001981
1982 // Flush all other data before writing the header.
1983 if (!out->Flush()) {
1984 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1985 return false;
1986 }
1987 // Write the header.
1988 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001989 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001990 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1991 return false;
1992 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001993 // Flush the header data.
1994 if (!out->Flush()) {
1995 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001996 return false;
1997 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001998
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001999 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2000 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2001 return false;
2002 }
2003 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2004
2005 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002006 return true;
2007}
2008
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002009bool OatWriter::WriteClassOffsets(OutputStream* out) {
2010 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2011 if (oat_dex_file.class_offsets_offset_ != 0u) {
2012 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
2013 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
2014 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2015 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
2016 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00002017 return false;
2018 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002019 if (!oat_dex_file.WriteClassOffsets(this, out)) {
2020 return false;
2021 }
2022 }
2023 }
2024 return true;
2025}
2026
2027bool OatWriter::WriteClasses(OutputStream* out) {
2028 for (OatClass& oat_class : oat_classes_) {
2029 if (!oat_class.Write(this, out, oat_data_offset_)) {
2030 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
2031 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00002032 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002033 }
2034 return true;
2035}
2036
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002037size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002038 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002039 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2040 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2041 return 0;
2042 }
2043 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002044 size_vmap_table_ = relative_offset - vmap_tables_offset;
2045
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002046 return relative_offset;
2047}
2048
2049size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002050 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002051 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002052
Ian Rogers848871b2013-08-05 10:56:33 -07002053 #define DO_TRAMPOLINE(field) \
2054 do { \
2055 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2056 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002057 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002058 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002059 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002060 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002061 return false; \
2062 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002063 size_ ## field += (field)->size(); \
2064 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002065 DCHECK_OFFSET(); \
2066 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002067
Ian Rogers848871b2013-08-05 10:56:33 -07002068 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002069 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002070 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002071 DO_TRAMPOLINE(quick_resolution_trampoline_);
2072 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2073 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002074 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002075 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002076}
2077
Ian Rogers3d504072014-03-01 09:16:49 -08002078size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002079 const size_t file_offset,
2080 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002081 #define VISIT(VisitorType) \
2082 do { \
2083 VisitorType visitor(this, out, file_offset, relative_offset); \
2084 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2085 return 0; \
2086 } \
2087 relative_offset = visitor.GetOffset(); \
2088 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002089
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002090 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002091
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002092 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002093
Vladimir Markob163bb72015-03-31 21:49:49 +01002094 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2095 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2096 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2097
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002098 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002099}
2100
Vladimir Marko944da602016-02-19 12:27:55 +00002101bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002102 // Get the elf file offset of the oat file.
2103 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2104 if (raw_file_offset == static_cast<off_t>(-1)) {
2105 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2106 return false;
2107 }
2108 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2109 return true;
2110}
2111
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002112bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2113 // Read the dex file header and perform minimal verification.
2114 uint8_t raw_header[sizeof(DexFile::Header)];
2115 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2116 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2117 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2118 return false;
2119 }
2120 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2121 return false;
2122 }
2123
2124 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2125 oat_dex_file->dex_file_size_ = header->file_size_;
2126 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2127 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2128 return true;
2129}
2130
2131bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2132 if (!DexFile::IsMagicValid(raw_header)) {
2133 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2134 return false;
2135 }
2136 if (!DexFile::IsVersionValid(raw_header)) {
2137 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2138 return false;
2139 }
2140 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2141 if (header->file_size_ < sizeof(DexFile::Header)) {
2142 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2143 << " File: " << location;
2144 return false;
2145 }
2146 return true;
2147}
2148
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002149bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002150 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002151
David Brazdil7b49e6c2016-09-01 11:06:18 +01002152 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002153
2154 // Write dex files.
2155 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002156 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002157 return false;
2158 }
2159 }
2160
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002161 CloseSources();
2162 return true;
2163}
2164
2165void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002166 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2167 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2168 }
2169 zipped_dex_files_.clear();
2170 zip_archives_.clear();
2171 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002172}
2173
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002174bool OatWriter::WriteDexFile(OutputStream* out,
2175 File* file,
2176 OatDexFile* oat_dex_file,
2177 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002178 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002179 return false;
2180 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002181 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002182 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002183 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2184 return false;
2185 }
2186 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002187 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002188 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002189 return false;
2190 }
2191 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002192 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002193 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002194 return false;
2195 }
2196 } else {
2197 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002198 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002199 return false;
2200 }
2201 }
2202
2203 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002204 if (kIsVdexEnabled) {
2205 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2206 vdex_size_ += oat_dex_file->dex_file_size_;
2207 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002208 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002209 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2210 oat_size_ += oat_dex_file->dex_file_size_;
2211 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002212 size_dex_file_ += oat_dex_file->dex_file_size_;
2213 return true;
2214}
2215
2216bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2217 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002218 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2219 size_t start_offset = RoundUp(initial_offset, 4);
2220 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2221 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002222
2223 // Seek to the start of the dex file and flush any pending operations in the stream.
2224 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002225 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2226 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002227 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002228 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002229 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2230 return false;
2231 }
2232 if (!out->Flush()) {
2233 PLOG(ERROR) << "Failed to flush before writing dex file."
2234 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2235 return false;
2236 }
2237 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002238 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002239 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002240 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002241 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2242 return false;
2243 }
2244
David Brazdil7b49e6c2016-09-01 11:06:18 +01002245 if (kIsVdexEnabled) {
2246 vdex_size_ = start_offset;
2247 } else {
2248 oat_size_ = start_offset;
2249 }
2250 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002251 return true;
2252}
2253
Jeff Hao608f2ce2016-10-19 11:17:11 -07002254bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2255 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2256 std::string error_msg;
2257 std::string location(oat_dex_file->GetLocation());
2258 std::unique_ptr<const DexFile> dex_file;
2259 if (oat_dex_file->source_.IsZipEntry()) {
2260 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2261 std::unique_ptr<MemMap> mem_map(
2262 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08002263 if (mem_map == nullptr) {
2264 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
2265 return false;
2266 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002267 dex_file = DexFile::Open(location,
2268 zip_entry->GetCrc32(),
2269 std::move(mem_map),
2270 /* verify */ true,
2271 /* verify_checksum */ true,
2272 &error_msg);
Nicolas Geoffray97fa9922017-03-09 13:13:25 +00002273 } else {
2274 CHECK(oat_dex_file->source_.IsRawFile())
2275 << static_cast<size_t>(oat_dex_file->source_.GetType());
Jeff Hao608f2ce2016-10-19 11:17:11 -07002276 File* raw_file = oat_dex_file->source_.GetRawFile();
2277 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2278 }
Jeff Haode197542017-02-03 10:48:13 -08002279 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08002280 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08002281 return false;
2282 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002283 Options options;
2284 options.output_to_memmap_ = true;
2285 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2286 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2287 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002288 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002289 return false;
2290 }
2291 // Set the checksum of the new oat dex file to be the original file's checksum.
2292 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2293 return true;
2294}
2295
David Brazdil7b49e6c2016-09-01 11:06:18 +01002296bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002297 File* file,
2298 OatDexFile* oat_dex_file,
2299 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002300 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2301 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002302
2303 // Extract the dex file and get the extracted size.
2304 std::string error_msg;
2305 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2306 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2307 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2308 return false;
2309 }
2310 if (file->Flush() != 0) {
2311 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2312 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2313 return false;
2314 }
2315 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2316 if (extracted_end == static_cast<off_t>(-1)) {
2317 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2318 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2319 return false;
2320 }
2321 if (extracted_end < static_cast<off_t>(start_offset)) {
2322 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2323 << " Start: " << start_offset
2324 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2325 return false;
2326 }
2327 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2328 if (extracted_size < sizeof(DexFile::Header)) {
2329 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2330 << extracted_size << " File: " << oat_dex_file->GetLocation();
2331 return false;
2332 }
2333
2334 // Read the dex file header and extract required data to OatDexFile.
2335 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2336 if (actual_offset != static_cast<off_t>(start_offset)) {
2337 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2338 << " Expected: " << start_offset
2339 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2340 return false;
2341 }
2342 if (!ReadDexFileHeader(file, oat_dex_file)) {
2343 return false;
2344 }
2345 if (extracted_size < oat_dex_file->dex_file_size_) {
2346 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2347 << " file size from header: " << oat_dex_file->dex_file_size_
2348 << " File: " << oat_dex_file->GetLocation();
2349 return false;
2350 }
2351
2352 // Override the checksum from header with the CRC from ZIP entry.
2353 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2354
2355 // Seek both file and stream to the end offset.
2356 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2357 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2358 if (actual_offset != static_cast<off_t>(end_offset)) {
2359 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2360 << " Expected: " << end_offset
2361 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2362 return false;
2363 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002364 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002365 if (actual_offset != static_cast<off_t>(end_offset)) {
2366 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2367 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2368 return false;
2369 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002370 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002371 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2372 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2373 return false;
2374 }
2375
2376 // If we extracted more than the size specified in the header, truncate the file.
2377 if (extracted_size > oat_dex_file->dex_file_size_) {
2378 if (file->SetLength(end_offset) != 0) {
2379 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002380 << " File: " << oat_dex_file->GetLocation()
2381 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002382 return false;
2383 }
2384 }
2385
2386 return true;
2387}
2388
David Brazdil7b49e6c2016-09-01 11:06:18 +01002389bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002390 File* file,
2391 OatDexFile* oat_dex_file,
2392 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002393 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2394 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002395
2396 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2397 if (input_offset != static_cast<off_t>(0)) {
2398 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2399 << " Expected: 0"
2400 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2401 return false;
2402 }
2403 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2404 return false;
2405 }
2406
2407 // Copy the input dex file using sendfile().
2408 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2409 PLOG(ERROR) << "Failed to copy dex file to oat file."
2410 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2411 return false;
2412 }
2413 if (file->Flush() != 0) {
2414 PLOG(ERROR) << "Failed to flush dex file."
2415 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2416 return false;
2417 }
2418
2419 // Check file position and seek the stream to the end offset.
2420 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2421 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2422 if (actual_offset != static_cast<off_t>(end_offset)) {
2423 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2424 << " Expected: " << end_offset
2425 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2426 return false;
2427 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002428 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002429 if (actual_offset != static_cast<off_t>(end_offset)) {
2430 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2431 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2432 return false;
2433 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002434 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002435 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2436 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2437 return false;
2438 }
2439
2440 return true;
2441}
2442
David Brazdil7b49e6c2016-09-01 11:06:18 +01002443bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002444 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002445 const uint8_t* dex_file,
2446 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002447 // Note: The raw data has already been checked to contain the header
2448 // and all the data that the header specifies as the file size.
2449 DCHECK(dex_file != nullptr);
2450 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2451 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2452
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002453 if (update_input_vdex) {
2454 // The vdex already contains the dex code, no need to write it again.
2455 } else {
2456 if (!out->WriteFully(dex_file, header->file_size_)) {
2457 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2458 << " to " << out->GetLocation();
2459 return false;
2460 }
2461 if (!out->Flush()) {
2462 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2463 << " File: " << oat_dex_file->GetLocation();
2464 return false;
2465 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002466 }
2467
2468 // Update dex file size and resize class offsets in the OatDexFile.
2469 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002470 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002471 oat_dex_file->dex_file_size_ = header->file_size_;
2472 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2473 return true;
2474}
2475
2476bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2477 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2478
David Brazdil181e1cc2016-09-01 16:38:47 +00002479 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2480 if (initial_offset == static_cast<off_t>(-1)) {
2481 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2482 return false;
2483 }
2484
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002485 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2486 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2487 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2488 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2489 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2490 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2491 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2492 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2493 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2494 return false;
2495 }
2496
2497 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2498 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2499
2500 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2501 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2502
2503 // Write OatDexFile.
2504 if (!oat_dex_file->Write(this, rodata)) {
2505 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2506 return false;
2507 }
2508 }
2509
David Brazdil181e1cc2016-09-01 16:38:47 +00002510 // Seek back to the initial position.
2511 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2512 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2513 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2514 return false;
2515 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002516
David Brazdilb92ba622016-09-01 16:00:30 +00002517 return true;
2518}
2519
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002520bool OatWriter::OpenDexFiles(
2521 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002522 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002523 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2524 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2525 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2526
2527 if (oat_dex_files_.empty()) {
2528 // Nothing to do.
2529 return true;
2530 }
2531
2532 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002533 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2534
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002535 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002536 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2537 length,
2538 PROT_READ | PROT_WRITE,
2539 MAP_SHARED,
2540 file->Fd(),
2541 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2542 /* low_4gb */ false,
2543 file->GetPath().c_str(),
2544 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002545 if (dex_files_map == nullptr) {
2546 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2547 << " error: " << error_msg;
2548 return false;
2549 }
2550 std::vector<std::unique_ptr<const DexFile>> dex_files;
2551 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2552 // Make sure no one messed with input files while we were copying data.
2553 // At the very least we need consistent file size and number of class definitions.
2554 const uint8_t* raw_dex_file =
2555 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2556 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2557 // Note: ValidateDexFileHeader() already logged an error message.
2558 LOG(ERROR) << "Failed to verify written dex file header!"
2559 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2560 << " ~ " << static_cast<const void*>(raw_dex_file);
2561 return false;
2562 }
2563 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2564 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2565 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2566 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2567 << " Output: " << file->GetPath();
2568 return false;
2569 }
2570 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2571 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2572 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2573 << " Output: " << file->GetPath();
2574 return false;
2575 }
2576
2577 // Now, open the dex file.
2578 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2579 oat_dex_file.dex_file_size_,
2580 oat_dex_file.GetLocation(),
2581 oat_dex_file.dex_file_location_checksum_,
2582 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002583 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002584 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002585 &error_msg));
2586 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002587 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2588 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002589 return false;
2590 }
2591 }
2592
2593 *opened_dex_files_map = std::move(dex_files_map);
2594 *opened_dex_files = std::move(dex_files);
2595 return true;
2596}
2597
2598bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002599 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002600 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2601 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2602
David Brazdil7b49e6c2016-09-01 11:06:18 +01002603 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2604 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2605 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2606 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2607 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2608 return false;
2609 }
2610
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002611 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2612 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2613 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002614 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2615
2616 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2617 oat_dex_file->class_offsets_.empty()) {
2618 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002619 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002620
2621 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2622 if (table_size == 0u) {
2623 continue;
2624 }
2625
2626 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002627 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002628 const DexFile& dex_file = *opened_dex_files[i];
2629 {
2630 std::unique_ptr<TypeLookupTable> type_lookup_table =
2631 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2632 type_lookup_table_oat_dex_files_.push_back(
2633 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2634 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2635 }
2636 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002637
2638 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002639 size_t initial_offset = oat_size_;
2640 size_t rodata_offset = RoundUp(initial_offset, 4);
2641 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002642
2643 if (padding_size != 0u) {
2644 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002645 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002646 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2647 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002648 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002649 return false;
2650 }
2651 }
2652
2653 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002654 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002655 DCHECK_EQ(table_size, table->RawDataLength());
2656
David Brazdil7b49e6c2016-09-01 11:06:18 +01002657 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002658 PLOG(ERROR) << "Failed to write lookup table."
2659 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002660 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002661 return false;
2662 }
2663
2664 oat_dex_file->lookup_table_offset_ = rodata_offset;
2665
David Brazdil7b49e6c2016-09-01 11:06:18 +01002666 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002667 size_oat_lookup_table_ += table_size;
2668 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002669 }
2670
David Brazdil7b49e6c2016-09-01 11:06:18 +01002671 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002672 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002673 << " File: " << oat_rodata->GetLocation();
2674 return false;
2675 }
2676
2677 return true;
2678}
2679
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002680bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002681 if (!kIsVdexEnabled) {
2682 return true;
2683 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002684 // Write checksums
2685 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2686 if (actual_offset != sizeof(VdexFile::Header)) {
2687 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2688 << " File: " << vdex_out->GetLocation();
2689 return false;
2690 }
2691
2692 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2693 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2694 if (!vdex_out->WriteFully(
2695 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2696 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2697 << vdex_out->GetLocation();
2698 return false;
2699 }
2700 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2701 }
2702
2703 // Write header.
2704 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002705 if (actual_offset != 0) {
2706 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2707 << " File: " << vdex_out->GetLocation();
2708 return false;
2709 }
2710
David Brazdil5d5a36b2016-09-14 15:34:10 +01002711 DCHECK_NE(vdex_dex_files_offset_, 0u);
2712 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2713
2714 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002715 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2716 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002717
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002718 VdexFile::Header vdex_header(oat_dex_files_.size(),
2719 dex_section_size,
2720 verifier_deps_section_size,
2721 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002722 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2723 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002724 return false;
2725 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002726 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002727
David Brazdil5d5a36b2016-09-14 15:34:10 +01002728 if (!vdex_out->Flush()) {
2729 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2730 << " File: " << vdex_out->GetLocation();
2731 return false;
2732 }
2733
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002734 return true;
2735}
2736
Vladimir Markof4da6752014-08-01 19:04:18 +01002737bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2738 static const uint8_t kPadding[] = {
2739 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2740 };
2741 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002742 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002743 return false;
2744 }
2745 size_code_alignment_ += aligned_code_delta;
2746 return true;
2747}
2748
Vladimir Marko944da602016-02-19 12:27:55 +00002749void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2750 DCHECK(dex_files_ != nullptr);
2751 DCHECK(relative_patcher_ != nullptr);
2752 DCHECK_NE(oat_data_offset_, 0u);
2753 if (image_writer_ != nullptr && !dex_files_->empty()) {
2754 // The oat data begin may not be initialized yet but the oat file offset is ready.
2755 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2756 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2757 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002758 }
2759}
2760
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002761OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2762 DexFileSource source,
2763 CreateTypeLookupTable create_type_lookup_table)
2764 : source_(source),
2765 create_type_lookup_table_(create_type_lookup_table),
2766 dex_file_size_(0),
2767 offset_(0),
2768 dex_file_location_size_(strlen(dex_file_location)),
2769 dex_file_location_data_(dex_file_location),
2770 dex_file_location_checksum_(0u),
2771 dex_file_offset_(0u),
2772 class_offsets_offset_(0u),
2773 lookup_table_offset_(0u),
2774 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002775}
2776
2777size_t OatWriter::OatDexFile::SizeOf() const {
2778 return sizeof(dex_file_location_size_)
2779 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002780 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002781 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002782 + sizeof(class_offsets_offset_)
2783 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002784}
2785
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002786void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2787 DCHECK_EQ(class_offsets_offset_, 0u);
2788 if (!class_offsets_.empty()) {
2789 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002790 size_t initial_offset = oat_writer->oat_size_;
2791 size_t offset = RoundUp(initial_offset, 4);
2792 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002793 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002794 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002795 }
2796}
2797
2798bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2799 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002800 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002801
Vladimir Markoe079e212016-05-25 12:49:49 +01002802 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002803 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002804 return false;
2805 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002806 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002807
Vladimir Markoe079e212016-05-25 12:49:49 +01002808 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002809 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002810 return false;
2811 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002812 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002813
Vladimir Markoe079e212016-05-25 12:49:49 +01002814 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002815 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002816 return false;
2817 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002818 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002819
Vladimir Markoe079e212016-05-25 12:49:49 +01002820 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002821 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002822 return false;
2823 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002824 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002825
Vladimir Markoe079e212016-05-25 12:49:49 +01002826 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002827 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2828 return false;
2829 }
2830 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2831
Vladimir Markoe079e212016-05-25 12:49:49 +01002832 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002833 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2834 return false;
2835 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002836 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002837
2838 return true;
2839}
2840
2841bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002842 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002843 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2844 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002845 return false;
2846 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002847 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002848 return true;
2849}
2850
Brian Carlstromba150c32013-08-27 17:31:03 -07002851OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002852 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002853 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002854 mirror::Class::Status status)
2855 : compiled_methods_(compiled_methods) {
2856 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002857 CHECK_LE(num_non_null_compiled_methods, num_methods);
2858
Brian Carlstrom265091e2013-01-30 14:08:26 -08002859 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002860 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2861
2862 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2863 // apply when there are 0 methods, we just arbitrarily say that 0
2864 // methods means kOatClassNoneCompiled and that we won't use
2865 // kOatClassAllCompiled unless there is at least one compiled
2866 // method. This means in an interpretter only system, we can assert
2867 // that all classes are kOatClassNoneCompiled.
2868 if (num_non_null_compiled_methods == 0) {
2869 type_ = kOatClassNoneCompiled;
2870 } else if (num_non_null_compiled_methods == num_methods) {
2871 type_ = kOatClassAllCompiled;
2872 } else {
2873 type_ = kOatClassSomeCompiled;
2874 }
2875
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002876 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002877 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002878 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002879
2880 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2881 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002882 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002883 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2884 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2885 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2886 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002887 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002888 method_bitmap_size_ = 0;
2889 }
2890
2891 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002892 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002893 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002894 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2895 } else {
2896 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2897 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2898 if (type_ == kOatClassSomeCompiled) {
2899 method_bitmap_->SetBit(i);
2900 }
2901 }
2902 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002903}
2904
Brian Carlstrom265091e2013-01-30 14:08:26 -08002905size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2906 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002907 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2908 if (method_offset == 0) {
2909 return 0;
2910 }
2911 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002912}
2913
2914size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2915 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002916 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002917}
2918
2919size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002920 return sizeof(status_)
2921 + sizeof(type_)
2922 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2923 + method_bitmap_size_
2924 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002925}
2926
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002927bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002928 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002929 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002930 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002931 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002932 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002933 return false;
2934 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002935 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002936
Vladimir Markoe079e212016-05-25 12:49:49 +01002937 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002938 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002939 return false;
2940 }
2941 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002942
Brian Carlstromba150c32013-08-27 17:31:03 -07002943 if (method_bitmap_size_ != 0) {
2944 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002945 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002946 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002947 return false;
2948 }
2949 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002950
Vladimir Markoe079e212016-05-25 12:49:49 +01002951 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002952 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002953 return false;
2954 }
2955 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2956 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002957
Vladimir Markoe079e212016-05-25 12:49:49 +01002958 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002959 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002960 return false;
2961 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002962 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002963 return true;
2964}
2965
Brian Carlstrome24fa612011-09-29 00:53:55 -07002966} // namespace art