blob: 8f5684b4d0270746b1ac6034831dca20628a253c [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000027#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070030#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070031#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000032#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000033#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "dex_file-inl.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070036#include "dexlayout.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "driver/compiler_driver.h"
38#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010039#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010042#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010043#include "linker/buffered_output_stream.h"
44#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000045#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000046#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/array.h"
48#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010049#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010051#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070052#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070053#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030055#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010056#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010057#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070058#include "verifier/method_verifier.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010059#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000060#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070061
62namespace art {
63
Vladimir Marko9bdf1082016-01-21 12:15:52 +000064namespace { // anonymous namespace
65
66typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
67
68const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
69 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
70}
71
Vladimir Markoe079e212016-05-25 12:49:49 +010072class ChecksumUpdatingOutputStream : public OutputStream {
73 public:
74 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
75 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
76
77 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
78 oat_header_->UpdateChecksum(buffer, byte_count);
79 return out_->WriteFully(buffer, byte_count);
80 }
81
82 off_t Seek(off_t offset, Whence whence) OVERRIDE {
83 return out_->Seek(offset, whence);
84 }
85
86 bool Flush() OVERRIDE {
87 return out_->Flush();
88 }
89
90 private:
91 OutputStream* const out_;
92 OatHeader* const oat_header_;
93};
94
Vladimir Marko0c737df2016-08-01 16:33:16 +010095inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
96 // We want to align the code rather than the preheader.
97 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
98 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
99 return aligned_code_offset - unaligned_code_offset;
100}
101
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000102} // anonymous namespace
103
104// Defines the location of the raw dex file to write.
105class OatWriter::DexFileSource {
106 public:
107 explicit DexFileSource(ZipEntry* zip_entry)
108 : type_(kZipEntry), source_(zip_entry) {
109 DCHECK(source_ != nullptr);
110 }
111
112 explicit DexFileSource(File* raw_file)
113 : type_(kRawFile), source_(raw_file) {
114 DCHECK(source_ != nullptr);
115 }
116
117 explicit DexFileSource(const uint8_t* dex_file)
118 : type_(kRawData), source_(dex_file) {
119 DCHECK(source_ != nullptr);
120 }
121
122 bool IsZipEntry() const { return type_ == kZipEntry; }
123 bool IsRawFile() const { return type_ == kRawFile; }
124 bool IsRawData() const { return type_ == kRawData; }
125
126 ZipEntry* GetZipEntry() const {
127 DCHECK(IsZipEntry());
128 DCHECK(source_ != nullptr);
129 return static_cast<ZipEntry*>(const_cast<void*>(source_));
130 }
131
132 File* GetRawFile() const {
133 DCHECK(IsRawFile());
134 DCHECK(source_ != nullptr);
135 return static_cast<File*>(const_cast<void*>(source_));
136 }
137
138 const uint8_t* GetRawData() const {
139 DCHECK(IsRawData());
140 DCHECK(source_ != nullptr);
141 return static_cast<const uint8_t*>(source_);
142 }
143
144 void Clear() {
145 type_ = kNone;
146 source_ = nullptr;
147 }
148
149 private:
150 enum Type {
151 kNone,
152 kZipEntry,
153 kRawFile,
154 kRawData,
155 };
156
157 Type type_;
158 const void* source_;
159};
160
Vladimir Marko49b0f452015-12-10 13:49:19 +0000161class OatWriter::OatClass {
162 public:
163 OatClass(size_t offset,
164 const dchecked_vector<CompiledMethod*>& compiled_methods,
165 uint32_t num_non_null_compiled_methods,
166 mirror::Class::Status status);
167 OatClass(OatClass&& src) = default;
168 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
169 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
170 size_t SizeOf() const;
171 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
172
173 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
174 return compiled_methods_[class_def_method_index];
175 }
176
177 // Offset of start of OatClass from beginning of OatHeader. It is
178 // used to validate file position when writing.
179 size_t offset_;
180
181 // CompiledMethods for each class_def_method_index, or null if no method is available.
182 dchecked_vector<CompiledMethod*> compiled_methods_;
183
184 // Offset from OatClass::offset_ to the OatMethodOffsets for the
185 // class_def_method_index. If 0, it means the corresponding
186 // CompiledMethod entry in OatClass::compiled_methods_ should be
187 // null and that the OatClass::type_ should be kOatClassBitmap.
188 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
189
190 // Data to write.
191
192 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
193 int16_t status_;
194
195 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
196 uint16_t type_;
197
198 uint32_t method_bitmap_size_;
199
200 // bit vector indexed by ClassDef method index. When
201 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
202 // method has an OatMethodOffsets in methods_offsets_, otherwise
203 // the entry was ommited to save space. If OatClassType::type_ is
204 // not is kOatClassBitmap, the bitmap will be null.
205 std::unique_ptr<BitVector> method_bitmap_;
206
207 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
208 // present in the OatClass. Note that some may be missing if
209 // OatClass::compiled_methods_ contains null values (and
210 // oat_method_offsets_offsets_from_oat_class_ should contain 0
211 // values in this case).
212 dchecked_vector<OatMethodOffsets> method_offsets_;
213 dchecked_vector<OatQuickMethodHeader> method_headers_;
214
215 private:
216 size_t GetMethodOffsetsRawSize() const {
217 return method_offsets_.size() * sizeof(method_offsets_[0]);
218 }
219
220 DISALLOW_COPY_AND_ASSIGN(OatClass);
221};
222
223class OatWriter::OatDexFile {
224 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 OatDexFile(const char* dex_file_location,
226 DexFileSource source,
227 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000228 OatDexFile(OatDexFile&& src) = default;
229
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000230 const char* GetLocation() const {
231 return dex_file_location_data_;
232 }
233
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000234 void ReserveClassOffsets(OatWriter* oat_writer);
235
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000237 bool Write(OatWriter* oat_writer, OutputStream* out) const;
238 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
239
240 // The source of the dex file.
241 DexFileSource source_;
242
243 // Whether to create the type lookup table.
244 CreateTypeLookupTable create_type_lookup_table_;
245
246 // Dex file size. Initialized when writing the dex file.
247 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248
249 // Offset of start of OatDexFile from beginning of OatHeader. It is
250 // used to validate file position when writing.
251 size_t offset_;
252
253 // Data to write.
254 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000256 uint32_t dex_file_location_checksum_;
257 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000258 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000259 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000260
261 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000262 dchecked_vector<uint32_t> class_offsets_;
263
264 private:
265 size_t GetClassOffsetsRawSize() const {
266 return class_offsets_.size() * sizeof(class_offsets_[0]);
267 }
268
269 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
270};
271
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100272#define DCHECK_OFFSET() \
273 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
274 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
275
276#define DCHECK_OFFSET_() \
277 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
278 << "file_offset=" << file_offset << " offset_=" << offset_
279
Jeff Hao608f2ce2016-10-19 11:17:11 -0700280OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000281 : write_state_(WriteState::kAddingDexFileSources),
282 timings_(timings),
283 raw_dex_files_(),
284 zip_archives_(),
285 zipped_dex_files_(),
286 zipped_dex_file_locations_(),
287 compiler_driver_(nullptr),
288 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800289 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000290 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100291 vdex_size_(0u),
292 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100293 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100294 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100295 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000296 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000297 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000298 bss_roots_offset_(0u),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000299 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000300 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100301 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700302 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100303 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000304 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700305 size_dex_file_alignment_(0),
306 size_executable_offset_alignment_(0),
307 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700308 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700309 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100310 size_verifier_deps_(0),
311 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100312 size_quickening_info_(0),
313 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700314 size_interpreter_to_interpreter_bridge_(0),
315 size_interpreter_to_compiled_code_bridge_(0),
316 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800317 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700318 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700319 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700320 size_quick_to_interpreter_bridge_(0),
321 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100322 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700323 size_code_(0),
324 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100325 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100326 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700327 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700328 size_oat_dex_file_location_size_(0),
329 size_oat_dex_file_location_data_(0),
330 size_oat_dex_file_location_checksum_(0),
331 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000332 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000333 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000334 size_oat_lookup_table_alignment_(0),
335 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000336 size_oat_class_offsets_alignment_(0),
337 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700338 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700339 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700340 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100341 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000342 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700343 absolute_patch_locations_(),
344 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000345}
346
347bool OatWriter::AddDexFileSource(const char* filename,
348 const char* location,
349 CreateTypeLookupTable create_type_lookup_table) {
350 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
351 uint32_t magic;
352 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700353 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
354 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000355 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
356 return false;
357 } else if (IsDexMagic(magic)) {
358 // The file is open for reading, not writing, so it's OK to let the File destructor
359 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700360 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000361 oat_dex_files_.emplace_back(location,
362 DexFileSource(raw_dex_files_.back().get()),
363 create_type_lookup_table);
364 } else if (IsZipMagic(magic)) {
365 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
366 return false;
367 }
368 } else {
369 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
370 return false;
371 }
372 return true;
373}
374
375// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700376bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000377 const char* location,
378 CreateTypeLookupTable create_type_lookup_table) {
379 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
380 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700381 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000382 ZipArchive* zip_archive = zip_archives_.back().get();
383 if (zip_archive == nullptr) {
384 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
385 << error_msg;
386 return false;
387 }
388 for (size_t i = 0; ; ++i) {
389 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
390 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
391 if (entry == nullptr) {
392 break;
393 }
394 zipped_dex_files_.push_back(std::move(entry));
395 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
396 const char* full_location = zipped_dex_file_locations_.back().c_str();
397 oat_dex_files_.emplace_back(full_location,
398 DexFileSource(zipped_dex_files_.back().get()),
399 create_type_lookup_table);
400 }
401 if (zipped_dex_file_locations_.empty()) {
402 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
403 return false;
404 }
405 return true;
406}
407
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000408// Add dex file source(s) from a vdex file specified by a file handle.
409bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
410 const char* location,
411 CreateTypeLookupTable create_type_lookup_table) {
412 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
413 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000414 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000415 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
416 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000417 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
418 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000419 }
420 if (!DexFile::IsMagicValid(current_dex_data)) {
421 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
422 return false;
423 }
424 // We used `zipped_dex_file_locations_` to keep the strings in memory.
425 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
426 const char* full_location = zipped_dex_file_locations_.back().c_str();
427 oat_dex_files_.emplace_back(full_location,
428 DexFileSource(current_dex_data),
429 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000430 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000431 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000432
433 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
434 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
435 return false;
436 }
437
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000438 if (oat_dex_files_.empty()) {
439 LOG(ERROR) << "No dex files in vdex file created from " << location;
440 return false;
441 }
442 return true;
443}
444
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000445// Add dex file source from raw memory.
446bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
447 const char* location,
448 uint32_t location_checksum,
449 CreateTypeLookupTable create_type_lookup_table) {
450 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
451 if (data.size() < sizeof(DexFile::Header)) {
452 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
453 << data.size() << " File: " << location;
454 return false;
455 }
456 if (!ValidateDexFileHeader(data.data(), location)) {
457 return false;
458 }
459 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
460 if (data.size() < header->file_size_) {
461 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
462 << " file size from header: " << header->file_size_ << " File: " << location;
463 return false;
464 }
465
466 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
467 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
468 return true;
469}
470
471dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
472 dchecked_vector<const char*> locations;
473 locations.reserve(oat_dex_files_.size());
474 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
475 locations.push_back(oat_dex_file.GetLocation());
476 }
477 return locations;
478}
479
480bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100481 File* vdex_file,
482 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000483 InstructionSet instruction_set,
484 const InstructionSetFeatures* instruction_set_features,
485 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800486 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000487 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
489 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
490 CHECK(write_state_ == WriteState::kAddingDexFileSources);
491
David Brazdil7b49e6c2016-09-01 11:06:18 +0100492 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
493 if (!RecordOatDataOffset(oat_rodata)) {
494 return false;
495 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000496
497 std::unique_ptr<MemMap> dex_files_map;
498 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100499
500 // Initialize VDEX and OAT headers.
501 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000502 // Reserve space for Vdex header and checksums.
503 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100504 }
505 size_t oat_data_offset = InitOatHeader(instruction_set,
506 instruction_set_features,
507 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
508 key_value_store);
509 oat_size_ = InitOatDexFiles(oat_data_offset);
510
511 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
512
513 if (kIsVdexEnabled) {
514 std::unique_ptr<BufferedOutputStream> vdex_out(
515 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100516 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000517 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100518 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
519 return false;
520 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100521 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000522 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100523 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000524 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100525 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
526 return false;
527 }
528
529 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
530 // difficult because we're not using the OutputStream directly.
531 if (!oat_dex_files_.empty()) {
532 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
533 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
534 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000535 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000536
David Brazdil7b49e6c2016-09-01 11:06:18 +0100537 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000538 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
539 return false;
540 }
541
David Brazdil7b49e6c2016-09-01 11:06:18 +0100542 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 for (OatDexFile& oat_dex_file : oat_dex_files_) {
544 oat_dex_file.ReserveClassOffsets(this);
545 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100546
David Brazdil7b49e6c2016-09-01 11:06:18 +0100547 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000548 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
549 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000550 }
551
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000552 *opened_dex_files_map = std::move(dex_files_map);
553 *opened_dex_files = std::move(dex_files);
554 write_state_ = WriteState::kPrepareLayout;
555 return true;
556}
557
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100558void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000559 CHECK(write_state_ == WriteState::kPrepareLayout);
560
Vladimir Marko944da602016-02-19 12:27:55 +0000561 relative_patcher_ = relative_patcher;
562 SetMultiOatRelativePatcherAdjustment();
563
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000564 if (compiling_boot_image_) {
565 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800566 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100567 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000568 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100569
David Brazdil7b49e6c2016-09-01 11:06:18 +0100570 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800571 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000572 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800573 offset = InitOatClasses(offset);
574 }
575 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000576 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100577 offset = InitOatMaps(offset);
578 }
579 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000580 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800581 offset = InitOatCode(offset);
582 }
583 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000584 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800585 offset = InitOatCodeDexFiles(offset);
586 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100587 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700588
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800589 if (!HasBootImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000590 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
591 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100592 }
593
Brian Carlstrome24fa612011-09-29 00:53:55 -0700594 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800595 if (compiling_boot_image_) {
596 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000597 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800598 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000599
600 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700601}
602
Ian Rogers0571d352011-11-03 19:51:38 -0700603OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700604}
605
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100606class OatWriter::DexMethodVisitor {
607 public:
608 DexMethodVisitor(OatWriter* writer, size_t offset)
609 : writer_(writer),
610 offset_(offset),
611 dex_file_(nullptr),
612 class_def_index_(DexFile::kDexNoIndex) {
613 }
614
615 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
616 DCHECK(dex_file_ == nullptr);
617 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
618 dex_file_ = dex_file;
619 class_def_index_ = class_def_index;
620 return true;
621 }
622
623 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
624
625 virtual bool EndClass() {
626 if (kIsDebugBuild) {
627 dex_file_ = nullptr;
628 class_def_index_ = DexFile::kDexNoIndex;
629 }
630 return true;
631 }
632
633 size_t GetOffset() const {
634 return offset_;
635 }
636
637 protected:
638 virtual ~DexMethodVisitor() { }
639
640 OatWriter* const writer_;
641
642 // The offset is usually advanced for each visited method by the derived class.
643 size_t offset_;
644
645 // The dex file and class def index are set in StartClass().
646 const DexFile* dex_file_;
647 size_t class_def_index_;
648};
649
650class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
651 public:
652 OatDexMethodVisitor(OatWriter* writer, size_t offset)
653 : DexMethodVisitor(writer, offset),
654 oat_class_index_(0u),
655 method_offsets_index_(0u) {
656 }
657
658 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
659 DexMethodVisitor::StartClass(dex_file, class_def_index);
660 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
661 method_offsets_index_ = 0u;
662 return true;
663 }
664
665 bool EndClass() {
666 ++oat_class_index_;
667 return DexMethodVisitor::EndClass();
668 }
669
670 protected:
671 size_t oat_class_index_;
672 size_t method_offsets_index_;
673};
674
675class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
676 public:
677 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
678 : DexMethodVisitor(writer, offset),
679 compiled_methods_(),
680 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000681 size_t num_classes = 0u;
682 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
683 num_classes += oat_dex_file.class_offsets_.size();
684 }
685 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100686 compiled_methods_.reserve(256u);
687 }
688
689 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
690 DexMethodVisitor::StartClass(dex_file, class_def_index);
691 compiled_methods_.clear();
692 num_non_null_compiled_methods_ = 0u;
693 return true;
694 }
695
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300696 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
697 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100698 // Fill in the compiled_methods_ array for methods that have a
699 // CompiledMethod. We track the number of non-null entries in
700 // num_non_null_compiled_methods_ since we only want to allocate
701 // OatMethodOffsets for the compiled methods.
702 uint32_t method_idx = it.GetMemberIndex();
703 CompiledMethod* compiled_method =
704 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
705 compiled_methods_.push_back(compiled_method);
706 if (compiled_method != nullptr) {
707 ++num_non_null_compiled_methods_;
708 }
709 return true;
710 }
711
712 bool EndClass() {
713 ClassReference class_ref(dex_file_, class_def_index_);
714 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
715 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700716 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100717 status = compiled_class->GetStatus();
718 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
719 status = mirror::Class::kStatusError;
720 } else {
721 status = mirror::Class::kStatusNotReady;
722 }
723
Vladimir Marko49b0f452015-12-10 13:49:19 +0000724 writer_->oat_classes_.emplace_back(offset_,
725 compiled_methods_,
726 num_non_null_compiled_methods_,
727 status);
728 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100729 return DexMethodVisitor::EndClass();
730 }
731
732 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000733 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100734 size_t num_non_null_compiled_methods_;
735};
736
737class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
738 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100739 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100740 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100741 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
742 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100743 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100744 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
745 }
746
747 bool EndClass() {
748 OatDexMethodVisitor::EndClass();
749 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100750 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100751 }
752 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100753 }
754
755 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700756 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000757 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100758 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
759
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100760 if (it.GetMethodCodeItem() != nullptr) {
761 current_quickening_info_offset_ += sizeof(uint32_t);
762 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100763 if (compiled_method != nullptr) {
764 // Derived from CompiledMethod.
765 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100766
Vladimir Marko35831e82015-09-11 11:59:18 +0100767 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
768 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800769 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800770
David Srbecky009e2a62015-04-15 02:46:30 +0100771 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100772 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800773 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000774 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000775 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
776 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800777 // Duplicate methods, we want the same code for both of them so that the oat writer puts
778 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800779 } else {
780 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100781 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800782 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000783 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100784 quick_code_offset = dedupe_map_.GetOrCreate(
785 compiled_method,
786 [this, &deduped, compiled_method, &it, thumb_offset]() {
787 deduped = false;
788 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
789 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800790 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100791
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100792 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000793 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100794 // TODO: Should this be a hard failure?
795 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700796 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000797 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
798 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100799 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000800 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100801 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800802 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100803
Elliott Hughes956af0f2014-12-11 14:34:28 -0800804 // Update quick method header.
805 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
806 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700807 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800808 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
809 // to 0-offset and we need to adjust it by code_offset.
810 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100811 if (!compiled_method->GetQuickCode().empty()) {
812 // If the code is compiled, we write the offset of the stack map relative
813 // to the code,
814 if (vmap_table_offset != 0u) {
815 vmap_table_offset += code_offset;
816 DCHECK_LT(vmap_table_offset, code_offset);
817 }
818 } else {
819 if (kIsVdexEnabled) {
820 // We write the offset in the .vdex file.
821 DCHECK_EQ(vmap_table_offset, 0u);
822 vmap_table_offset = current_quickening_info_offset_;
823 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
824 current_quickening_info_offset_ += map.size() * sizeof(map.front());
825 } else {
826 // We write the offset of the quickening info relative to the code.
827 vmap_table_offset += code_offset;
828 DCHECK_LT(vmap_table_offset, code_offset);
829 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800830 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800831 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
832 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
833 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100834 *method_header = OatQuickMethodHeader(vmap_table_offset,
835 frame_size_in_bytes,
836 core_spill_mask,
837 fp_spill_mask,
838 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100839
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000840 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800841 // Update offsets. (Checksum is updated when writing.)
842 offset_ += sizeof(*method_header); // Method header is prepended before code.
843 offset_ += code_size;
844 // Record absolute patch locations.
845 if (!compiled_method->GetPatches().empty()) {
846 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
847 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000848 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100849 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100850 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000851 if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
852 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
853 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
854 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000855 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
856 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
857 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
858 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100859 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100860 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800861 }
Alex Light78382fa2014-06-06 15:45:32 -0700862
David Srbecky91cc06c2016-03-07 16:13:58 +0000863 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000864 // Exclude quickened dex methods (code_size == 0) since they have no native code.
865 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
866 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800867 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000868 debug::MethodDebugInfo info = debug::MethodDebugInfo();
869 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000870 info.dex_file = dex_file_;
871 info.class_def_index = class_def_index_;
872 info.dex_method_index = it.GetMemberIndex();
873 info.access_flags = it.GetMethodAccessFlags();
874 info.code_item = it.GetMethodCodeItem();
875 info.isa = compiled_method->GetInstructionSet();
876 info.deduped = deduped;
877 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
878 info.is_optimized = method_header->IsOptimized();
879 info.is_code_address_text_relative = true;
880 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
881 info.code_size = code_size;
882 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
883 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
884 info.cfi = compiled_method->GetCFIInfo();
885 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100886 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100887
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100888 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
889 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
890 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100891 ++method_offsets_index_;
892 }
893
894 return true;
895 }
896
897 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000898 struct CodeOffsetsKeyComparator {
899 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100900 // Code is deduplicated by CompilerDriver, compare only data pointers.
901 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
902 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000903 }
904 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100905 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
906 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000907 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100908 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
909 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000910 }
911 return false;
912 }
913 };
914
David Srbecky009e2a62015-04-15 02:46:30 +0100915 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
916 const ClassDataItemIterator& it,
917 uint32_t thumb_offset) {
918 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100919 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100920 offset_ += CodeAlignmentSize(offset_, *compiled_method);
921 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100922 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
923 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
924 }
925
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100926 // Deduplication is already done on a pointer basis by the compiler driver,
927 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100928 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100929
David Srbecky009e2a62015-04-15 02:46:30 +0100930 // Cache of compiler's --debuggable option.
931 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100932
933 // Offset in the vdex file for the quickening info.
934 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100935};
936
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100937class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
938 public:
939 InitMapMethodVisitor(OatWriter* writer, size_t offset)
940 : OatDexMethodVisitor(writer, offset) {
941 }
942
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700943 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700944 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000945 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
947
948 if (compiled_method != nullptr) {
949 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100950 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
951 // be in the vdex file.
952 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700953 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100954
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100955 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
956 uint32_t map_size = map.size() * sizeof(map[0]);
957 if (map_size != 0u) {
958 size_t offset = dedupe_map_.GetOrCreate(
959 map.data(),
960 [this, map_size]() {
961 uint32_t new_offset = offset_;
962 offset_ += map_size;
963 return new_offset;
964 });
965 // Code offset is not initialized yet, so set the map offset to 0u-offset.
966 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700967 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100968 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969 }
970 ++method_offsets_index_;
971 }
972
973 return true;
974 }
975
976 private:
977 // Deduplication is already done on a pointer basis by the compiler driver,
978 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100979 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100980};
981
982class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
983 public:
984 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800985 : OatDexMethodVisitor(writer, offset),
986 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100987 }
988
989 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700990 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800991 const DexFile::TypeId& type_id =
992 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
993 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
994 // Skip methods that are not in the image.
995 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
996 return true;
997 }
998
Vladimir Marko49b0f452015-12-10 13:49:19 +0000999 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001000 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1001
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001002 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001003 if (compiled_method != nullptr) {
1004 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1005 offsets = oat_class->method_offsets_[method_offsets_index_];
1006 ++method_offsets_index_;
1007 }
1008
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001009 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001010 // Unchecked as we hold mutator_lock_ on entry.
1011 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001012 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001013 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
1014 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001015 ArtMethod* method;
1016 if (writer_->HasBootImage()) {
1017 const InvokeType invoke_type = it.GetMethodInvokeType(
1018 dex_file_->GetClassDef(class_def_index_));
1019 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1020 *dex_file_,
1021 it.GetMemberIndex(),
1022 dex_cache,
1023 ScopedNullHandle<mirror::ClassLoader>(),
1024 nullptr,
1025 invoke_type);
1026 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001027 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001028 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001029 soa.Self()->AssertPendingException();
1030 mirror::Throwable* exc = soa.Self()->GetException();
1031 std::string dump = exc->Dump();
1032 LOG(FATAL) << dump;
1033 UNREACHABLE();
1034 }
1035 } else {
1036 // Should already have been resolved by the compiler, just peek into the dex cache.
1037 // It may not be resolved if the class failed to verify, in this case, don't set the
1038 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1039 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001040 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001041 if (method != nullptr &&
1042 compiled_method != nullptr &&
1043 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001044 method->SetEntryPointFromQuickCompiledCodePtrSize(
1045 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1046 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001047
1048 return true;
1049 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001050
1051 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001052 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001053};
1054
1055class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1056 public:
1057 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001058 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001059 : OatDexMethodVisitor(writer, relative_offset),
1060 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001061 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001062 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001063 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001064 class_linker_(Runtime::Current()->GetClassLinker()),
1065 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001066 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001067 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001068 // If we're creating the image, the address space must be ready so that we can apply patches.
1069 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001070 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001071 }
1072
Vladimir Markof4da6752014-08-01 19:04:18 +01001073 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001074 }
1075
1076 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001077 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001078 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1079 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001080 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001081 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001082 }
1083 return true;
1084 }
1085
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001086 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001087 bool result = OatDexMethodVisitor::EndClass();
1088 if (oat_class_index_ == writer_->oat_classes_.size()) {
1089 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001090 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001091 if (UNLIKELY(offset_ == 0u)) {
1092 PLOG(ERROR) << "Failed to write final relative call thunks";
1093 result = false;
1094 }
1095 }
1096 return result;
1097 }
1098
1099 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001100 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001101 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001102 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1103
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001104 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001105 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001106 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001107 size_t file_offset = file_offset_;
1108 OutputStream* out = out_;
1109
Vladimir Marko35831e82015-09-11 11:59:18 +01001110 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1111 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001112
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001113 // Deduplicate code arrays.
1114 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1115 if (method_offsets.code_offset_ > offset_) {
1116 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1117 if (offset_ == 0u) {
1118 ReportWriteFailure("relative call thunk", it);
1119 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001120 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001121 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1122 if (alignment_size != 0) {
1123 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001124 ReportWriteFailure("code alignment padding", it);
1125 return false;
1126 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001127 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001128 DCHECK_OFFSET_();
1129 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001130 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001131 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1132 DCHECK_EQ(method_offsets.code_offset_,
1133 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001134 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001135 const OatQuickMethodHeader& method_header =
1136 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001137 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001138 ReportWriteFailure("method header", it);
1139 return false;
1140 }
1141 writer_->size_method_header_ += sizeof(method_header);
1142 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001143 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001144
1145 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001146 patched_code_.assign(quick_code.begin(), quick_code.end());
1147 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001148 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001149 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001150 switch (patch.GetType()) {
1151 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001152 // NOTE: Relative calls across oat files are not supported.
1153 uint32_t target_offset = GetTargetOffset(patch);
1154 writer_->relative_patcher_->PatchCall(&patched_code_,
1155 literal_offset,
1156 offset_ + literal_offset,
1157 target_offset);
1158 break;
1159 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001160 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001161 uint32_t target_offset = GetDexCacheOffset(patch);
1162 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1163 patch,
1164 offset_ + literal_offset,
1165 target_offset);
1166 break;
1167 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001168 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001169 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1170 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1171 patch,
1172 offset_ + literal_offset,
1173 target_offset);
1174 break;
1175 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001176 case LinkerPatch::Type::kStringBssEntry: {
1177 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1178 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1179 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1180 patch,
1181 offset_ + literal_offset,
1182 target_offset);
1183 break;
1184 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001185 case LinkerPatch::Type::kTypeRelative: {
1186 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1187 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1188 patch,
1189 offset_ + literal_offset,
1190 target_offset);
1191 break;
1192 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001193 case LinkerPatch::Type::kTypeBssEntry: {
1194 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1195 uint32_t target_offset = writer_->bss_type_entries_.Get(ref);
1196 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1197 patch,
1198 offset_ + literal_offset,
1199 target_offset);
1200 break;
1201 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001202 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001203 uint32_t target_offset = GetTargetOffset(patch);
1204 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1205 break;
1206 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001207 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001208 ArtMethod* method = GetTargetMethod(patch);
1209 PatchMethodAddress(&patched_code_, literal_offset, method);
1210 break;
1211 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001212 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001213 mirror::String* string = GetTargetString(patch);
1214 PatchObjectAddress(&patched_code_, literal_offset, string);
1215 break;
1216 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001217 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001218 mirror::Class* type = GetTargetType(patch);
1219 PatchObjectAddress(&patched_code_, literal_offset, type);
1220 break;
1221 }
1222 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001223 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001224 break;
1225 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001226 }
1227 }
1228 }
1229
Vladimir Markoe079e212016-05-25 12:49:49 +01001230 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001231 ReportWriteFailure("method code", it);
1232 return false;
1233 }
1234 writer_->size_code_ += code_size;
1235 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001236 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001237 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001238 ++method_offsets_index_;
1239 }
1240
1241 return true;
1242 }
1243
1244 private:
1245 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001246 const size_t file_offset_;
1247 const ScopedObjectAccess soa_;
1248 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001249 ClassLinker* const class_linker_;
1250 mirror::DexCache* dex_cache_;
1251 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001252
1253 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1254 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001255 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001256 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001257
Mathieu Chartiere401d142015-04-22 13:56:20 -07001258 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001259 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001260 MethodReference ref = patch.TargetMethod();
1261 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001262 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1263 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001264 ArtMethod* method = dex_cache->GetResolvedMethod(
1265 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001266 CHECK(method != nullptr);
1267 return method;
1268 }
1269
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001270 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001271 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1272 // If there's no new compiled code, either we're compiling an app and the target method
1273 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001274 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001275 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001276 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001277 PointerSize size =
1278 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001279 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1280 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001281 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001282 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1283 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1284 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1285 target_offset = PointerToLowMemUInt32(oat_code_offset);
1286 } else {
1287 target_offset = target->IsNative()
1288 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1289 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1290 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001291 }
1292 return target_offset;
1293 }
1294
Vladimir Marko052164a2016-04-27 13:54:18 +01001295 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001296 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001297 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001298 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001299 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1300 }
1301
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001302 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001303 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001304 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1305 CHECK(type != nullptr);
1306 return type;
1307 }
1308
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001309 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001310 ScopedObjectAccessUnchecked soa(Thread::Current());
1311 StackHandleScope<1> hs(soa.Self());
1312 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1313 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1314 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1315 patch.TargetStringIndex(),
1316 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001317 DCHECK(string != nullptr);
1318 DCHECK(writer_->HasBootImage() ||
1319 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1320 return string;
1321 }
1322
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001323 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001324 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001325 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1326 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1327 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1328 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001329 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001330 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001331 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1332 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001333 }
1334 }
1335
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001336 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001337 DCHECK(writer_->HasBootImage());
1338 object = writer_->image_writer_->GetImageAddress(object);
1339 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1340 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1341 // TODO: Clean up offset types. The target offset must be treated as signed.
1342 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1343 }
1344
Vladimir Markof4da6752014-08-01 19:04:18 +01001345 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001346 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001347 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001348 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001349 } else {
1350 // NOTE: We're using linker patches for app->boot references when the image can
1351 // be relocated and therefore we need to emit .oat_patches. We're not using this
1352 // for app->app references, so check that the object is in the image space.
1353 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001354 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001355 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001356 uint32_t address = PointerToLowMemUInt32(object);
1357 DCHECK_LE(offset + 4, code->size());
1358 uint8_t* data = &(*code)[offset];
1359 data[0] = address & 0xffu;
1360 data[1] = (address >> 8) & 0xffu;
1361 data[2] = (address >> 16) & 0xffu;
1362 data[3] = (address >> 24) & 0xffu;
1363 }
1364
Mathieu Chartiere401d142015-04-22 13:56:20 -07001365 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001366 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001367 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001368 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001369 } else if (kIsDebugBuild) {
1370 // NOTE: We're using linker patches for app->boot references when the image can
1371 // be relocated and therefore we need to emit .oat_patches. We're not using this
1372 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001373 std::vector<gc::space::ImageSpace*> image_spaces =
1374 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1375 bool contains_method = false;
1376 for (gc::space::ImageSpace* image_space : image_spaces) {
1377 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1378 contains_method |=
1379 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1380 }
1381 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001382 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001383 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001384 uint32_t address = PointerToLowMemUInt32(method);
1385 DCHECK_LE(offset + 4, code->size());
1386 uint8_t* data = &(*code)[offset];
1387 data[0] = address & 0xffu;
1388 data[1] = (address >> 8) & 0xffu;
1389 data[2] = (address >> 16) & 0xffu;
1390 data[3] = (address >> 24) & 0xffu;
1391 }
1392
Vladimir Markof4da6752014-08-01 19:04:18 +01001393 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001394 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001395 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001396 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001397 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1398 // TODO: Clean up offset types.
1399 // The target_offset must be treated as signed for cross-oat patching.
1400 const void* target = reinterpret_cast<const void*>(
1401 writer_->image_writer_->GetOatDataBegin(oat_index) +
1402 static_cast<int32_t>(target_offset));
1403 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001404 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001405 DCHECK_LE(offset + 4, code->size());
1406 uint8_t* data = &(*code)[offset];
1407 data[0] = address & 0xffu;
1408 data[1] = (address >> 8) & 0xffu;
1409 data[2] = (address >> 16) & 0xffu;
1410 data[3] = (address >> 24) & 0xffu;
1411 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001412};
1413
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001414class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1415 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001416 WriteMapMethodVisitor(OatWriter* writer,
1417 OutputStream* out,
1418 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001419 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420 : OatDexMethodVisitor(writer, relative_offset),
1421 out_(out),
1422 file_offset_(file_offset) {
1423 }
1424
1425 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001426 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001427 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1428
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001429 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001430 size_t file_offset = file_offset_;
1431 OutputStream* out = out_;
1432
Mingyao Yang063fc772016-08-02 11:02:54 -07001433 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001434 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001435 ++method_offsets_index_;
1436
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001437 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1438 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1439 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001440 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001441
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001442 // If vdex is enabled, only emit the map for compiled code. The quickening info
1443 // is emitted in the vdex already.
1444 if (map_offset != 0u &&
1445 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001446 // Transform map_offset to actual oat data offset.
1447 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1448 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001449 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001450
1451 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1452 size_t map_size = map.size() * sizeof(map[0]);
1453 if (map_offset == offset_) {
1454 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001455 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001456 ReportWriteFailure(it);
1457 return false;
1458 }
1459 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001460 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001461 }
1462 DCHECK_OFFSET_();
1463 }
1464
1465 return true;
1466 }
1467
1468 private:
1469 OutputStream* const out_;
1470 size_t const file_offset_;
1471
1472 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001473 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001474 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001475 }
1476};
1477
1478// Visit all methods from all classes in all dex files with the specified visitor.
1479bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1480 for (const DexFile* dex_file : *dex_files_) {
1481 const size_t class_def_count = dex_file->NumClassDefs();
1482 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1483 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1484 return false;
1485 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001486 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1487 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1488 const uint8_t* class_data = dex_file->GetClassData(class_def);
1489 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1490 ClassDataItemIterator it(*dex_file, class_data);
1491 while (it.HasNextStaticField()) {
1492 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001493 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001494 while (it.HasNextInstanceField()) {
1495 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001496 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001497 size_t class_def_method_index = 0u;
1498 while (it.HasNextDirectMethod()) {
1499 if (!visitor->VisitMethod(class_def_method_index, it)) {
1500 return false;
1501 }
1502 ++class_def_method_index;
1503 it.Next();
1504 }
1505 while (it.HasNextVirtualMethod()) {
1506 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1507 return false;
1508 }
1509 ++class_def_method_index;
1510 it.Next();
1511 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001512 }
1513 }
1514 if (UNLIKELY(!visitor->EndClass())) {
1515 return false;
1516 }
1517 }
1518 }
1519 return true;
1520}
1521
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001522size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1523 const InstructionSetFeatures* instruction_set_features,
1524 uint32_t num_dex_files,
1525 SafeMap<std::string, std::string>* key_value_store) {
1526 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1527 oat_header_.reset(OatHeader::Create(instruction_set,
1528 instruction_set_features,
1529 num_dex_files,
1530 key_value_store));
1531 size_oat_header_ += sizeof(OatHeader);
1532 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001533 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001534}
1535
1536size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001537 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1538 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001539 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001540 oat_dex_file.offset_ = offset;
1541 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001542 }
1543 return offset;
1544}
1545
Brian Carlstrom389efb02012-01-11 12:06:26 -08001546size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001547 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001548 InitOatClassesMethodVisitor visitor(this, offset);
1549 bool success = VisitDexMethods(&visitor);
1550 CHECK(success);
1551 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001552
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001553 // Update oat_dex_files_.
1554 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001555 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1556 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001557 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001558 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001559 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001560 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001561 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001562 CHECK(oat_class_it == oat_classes_.end());
1563
1564 return offset;
1565}
1566
1567size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001568 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1569 return offset;
1570 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001571 InitMapMethodVisitor visitor(this, offset);
1572 bool success = VisitDexMethods(&visitor);
1573 DCHECK(success);
1574 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001575
Brian Carlstrome24fa612011-09-29 00:53:55 -07001576 return offset;
1577}
1578
1579size_t OatWriter::InitOatCode(size_t offset) {
1580 // calculate the offsets within OatHeader to executable code
1581 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001582 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001583 // required to be on a new page boundary
1584 offset = RoundUp(offset, kPageSize);
1585 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001586 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001587 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001588 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001589
Ian Rogers848871b2013-08-05 10:56:33 -07001590 #define DO_TRAMPOLINE(field, fn_name) \
1591 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001592 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1593 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001594 (field) = compiler_driver_->Create ## fn_name(); \
1595 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001596
Ian Rogers848871b2013-08-05 10:56:33 -07001597 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001598 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001599 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001600 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1601 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001602
Ian Rogers848871b2013-08-05 10:56:33 -07001603 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001604 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001605 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1606 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1607 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001608 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001609 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001610 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001611 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001612 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001613 return offset;
1614}
1615
1616size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001617 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1618 return offset;
1619 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001620 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1621 bool success = VisitDexMethods(&code_visitor);
1622 DCHECK(success);
1623 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001624
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001625 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001626 InitImageMethodVisitor image_visitor(this, offset);
1627 success = VisitDexMethods(&image_visitor);
1628 DCHECK(success);
1629 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001630 }
Logan Chien8b977d32012-02-21 19:14:55 +08001631
Brian Carlstrome24fa612011-09-29 00:53:55 -07001632 return offset;
1633}
1634
Vladimir Markoaad75c62016-10-03 08:46:48 +00001635void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1636 DCHECK(!HasBootImage());
1637
1638 // Allocate space for app dex cache arrays in the .bss section.
1639 bss_start_ = RoundUp(oat_size_, kPageSize);
1640 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1641 bss_size_ = 0u;
1642 for (const DexFile* dex_file : *dex_files_) {
1643 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1644 DexCacheArraysLayout layout(pointer_size, dex_file);
1645 bss_size_ += layout.Size();
1646 }
1647
1648 bss_roots_offset_ = bss_size_;
1649
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001650 // Prepare offsets for .bss Class entries.
1651 for (auto& entry : bss_type_entries_) {
1652 DCHECK_EQ(entry.second, 0u);
1653 entry.second = bss_start_ + bss_size_;
1654 bss_size_ += sizeof(GcRoot<mirror::Class>);
1655 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001656 // Prepare offsets for .bss String entries.
1657 for (auto& entry : bss_string_entries_) {
1658 DCHECK_EQ(entry.second, 0u);
1659 entry.second = bss_start_ + bss_size_;
1660 bss_size_ += sizeof(GcRoot<mirror::String>);
1661 }
1662}
1663
David Srbeckybc90fd02015-04-22 19:40:27 +01001664bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001665 CHECK(write_state_ == WriteState::kWriteRoData);
1666
Vladimir Markoe079e212016-05-25 12:49:49 +01001667 // Wrap out to update checksum with each write.
1668 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1669 out = &checksum_updating_out;
1670
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001671 if (!WriteClassOffsets(out)) {
1672 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001673 return false;
1674 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001675
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001676 if (!WriteClasses(out)) {
1677 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001678 return false;
1679 }
1680
Vladimir Markof4da6752014-08-01 19:04:18 +01001681 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001682 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001683 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001684 return false;
1685 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001686 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001687 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001688 relative_offset = WriteMaps(out, file_offset, relative_offset);
1689 if (relative_offset == 0) {
1690 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1691 return false;
1692 }
1693
David Srbeckybc90fd02015-04-22 19:40:27 +01001694 // Write padding.
1695 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1696 relative_offset += size_executable_offset_alignment_;
1697 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1698 size_t expected_file_offset = file_offset + relative_offset;
1699 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1700 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1701 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1702 return 0;
1703 }
1704 DCHECK_OFFSET();
1705
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001706 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001707 return true;
1708}
1709
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001710class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1711 public:
1712 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1713 : DexMethodVisitor(writer, offset),
1714 out_(out),
1715 written_bytes_(0u) {}
1716
1717 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1718 const ClassDataItemIterator& it) {
1719 if (it.GetMethodCodeItem() == nullptr) {
1720 // No CodeItem. Native or abstract method.
1721 return true;
1722 }
1723
1724 uint32_t method_idx = it.GetMemberIndex();
1725 CompiledMethod* compiled_method =
1726 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1727
1728 uint32_t length = 0;
1729 const uint8_t* data = nullptr;
1730 // VMap only contains quickening info if this method is not compiled.
1731 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1732 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1733 data = map.data();
1734 length = map.size() * sizeof(map.front());
1735 }
1736
1737 if (!out_->WriteFully(&length, sizeof(length)) ||
1738 !out_->WriteFully(data, length)) {
1739 PLOG(ERROR) << "Failed to write quickening info for "
1740 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1741 return false;
1742 }
1743 offset_ += sizeof(length) + length;
1744 written_bytes_ += sizeof(length) + length;
1745 return true;
1746 }
1747
1748 size_t GetNumberOfWrittenBytes() const {
1749 return written_bytes_;
1750 }
1751
1752 private:
1753 OutputStream* const out_;
1754 size_t written_bytes_;
1755};
1756
1757bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1758 if (!kIsVdexEnabled) {
1759 return true;
1760 }
1761
1762 size_t initial_offset = vdex_size_;
1763 size_t start_offset = RoundUp(initial_offset, 4u);
1764
1765 vdex_size_ = start_offset;
1766 vdex_quickening_info_offset_ = vdex_size_;
1767 size_quickening_info_alignment_ = start_offset - initial_offset;
1768
1769 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1770 if (actual_offset != static_cast<off_t>(start_offset)) {
1771 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1772 << " Expected: " << start_offset
1773 << " Output: " << vdex_out->GetLocation();
1774 return false;
1775 }
1776
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001777 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1778 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1779 if (!VisitDexMethods(&visitor)) {
1780 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1781 return false;
1782 }
1783
1784 if (!vdex_out->Flush()) {
1785 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1786 << " File: " << vdex_out->GetLocation();
1787 return false;
1788 }
1789 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1790 } else {
1791 // We know we did not quicken.
1792 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001793 }
1794
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001795 vdex_size_ += size_quickening_info_;
1796 return true;
1797}
1798
David Brazdil5d5a36b2016-09-14 15:34:10 +01001799bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1800 if (!kIsVdexEnabled) {
1801 return true;
1802 }
1803
1804 if (verifier_deps == nullptr) {
1805 // Nothing to write. Record the offset, but no need
1806 // for alignment.
1807 vdex_verifier_deps_offset_ = vdex_size_;
1808 return true;
1809 }
1810
1811 size_t initial_offset = vdex_size_;
1812 size_t start_offset = RoundUp(initial_offset, 4u);
1813
1814 vdex_size_ = start_offset;
1815 vdex_verifier_deps_offset_ = vdex_size_;
1816 size_verifier_deps_alignment_ = start_offset - initial_offset;
1817
1818 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1819 if (actual_offset != static_cast<off_t>(start_offset)) {
1820 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1821 << " Expected: " << start_offset
1822 << " Output: " << vdex_out->GetLocation();
1823 return false;
1824 }
1825
1826 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001827 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001828
1829 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1830 PLOG(ERROR) << "Failed to write verifier deps."
1831 << " File: " << vdex_out->GetLocation();
1832 return false;
1833 }
1834 if (!vdex_out->Flush()) {
1835 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1836 << " File: " << vdex_out->GetLocation();
1837 return false;
1838 }
1839
1840 size_verifier_deps_ = buffer.size();
1841 vdex_size_ += size_verifier_deps_;
1842 return true;
1843}
1844
David Srbeckybc90fd02015-04-22 19:40:27 +01001845bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001846 CHECK(write_state_ == WriteState::kWriteText);
1847
Vladimir Markoe079e212016-05-25 12:49:49 +01001848 // Wrap out to update checksum with each write.
1849 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1850 out = &checksum_updating_out;
1851
Vladimir Marko944da602016-02-19 12:27:55 +00001852 SetMultiOatRelativePatcherAdjustment();
1853
David Srbeckybc90fd02015-04-22 19:40:27 +01001854 const size_t file_offset = oat_data_offset_;
1855 size_t relative_offset = oat_header_->GetExecutableOffset();
1856 DCHECK_OFFSET();
1857
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001858 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001859 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001860 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001861 return false;
1862 }
1863
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001864 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1865 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001866 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001867 return false;
1868 }
1869
Vladimir Markof4da6752014-08-01 19:04:18 +01001870 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001871 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001872 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1873 return false;
1874 }
1875
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001876 if (kIsDebugBuild) {
1877 uint32_t size_total = 0;
1878 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001879 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1880 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001881
David Brazdil7b49e6c2016-09-01 11:06:18 +01001882 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001883 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001884 DO_STAT(size_dex_file_alignment_);
1885 DO_STAT(size_executable_offset_alignment_);
1886 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001887 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001888 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001889 DO_STAT(size_verifier_deps_);
1890 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001891 DO_STAT(size_quickening_info_);
1892 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001893 DO_STAT(size_interpreter_to_interpreter_bridge_);
1894 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1895 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001896 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001897 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001898 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001899 DO_STAT(size_quick_to_interpreter_bridge_);
1900 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001901 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001902 DO_STAT(size_code_);
1903 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001904 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001905 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001906 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001907 DO_STAT(size_oat_dex_file_location_size_);
1908 DO_STAT(size_oat_dex_file_location_data_);
1909 DO_STAT(size_oat_dex_file_location_checksum_);
1910 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001911 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001912 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001913 DO_STAT(size_oat_lookup_table_alignment_);
1914 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001915 DO_STAT(size_oat_class_offsets_alignment_);
1916 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001917 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001918 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001919 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001920 DO_STAT(size_oat_class_method_offsets_);
1921 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001922
David Brazdil7b49e6c2016-09-01 11:06:18 +01001923 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1924
1925 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1926 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001927 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001928
David Brazdil7b49e6c2016-09-01 11:06:18 +01001929 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1930 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001931
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001932 write_state_ = WriteState::kWriteHeader;
1933 return true;
1934}
1935
1936bool OatWriter::WriteHeader(OutputStream* out,
1937 uint32_t image_file_location_oat_checksum,
1938 uintptr_t image_file_location_oat_begin,
1939 int32_t image_patch_delta) {
1940 CHECK(write_state_ == WriteState::kWriteHeader);
1941
1942 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1943 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001944 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001945 CHECK_EQ(image_patch_delta, 0);
1946 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1947 } else {
1948 CHECK_ALIGNED(image_patch_delta, kPageSize);
1949 oat_header_->SetImagePatchDelta(image_patch_delta);
1950 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001951 oat_header_->UpdateChecksumWithHeaderData();
1952
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001953 const size_t file_offset = oat_data_offset_;
1954
1955 off_t current_offset = out->Seek(0, kSeekCurrent);
1956 if (current_offset == static_cast<off_t>(-1)) {
1957 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1958 return false;
1959 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001960 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001961 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1962 return false;
1963 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001964 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001965
1966 // Flush all other data before writing the header.
1967 if (!out->Flush()) {
1968 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1969 return false;
1970 }
1971 // Write the header.
1972 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001973 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001974 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1975 return false;
1976 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001977 // Flush the header data.
1978 if (!out->Flush()) {
1979 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001980 return false;
1981 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001982
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001983 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1984 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1985 return false;
1986 }
1987 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1988
1989 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001990 return true;
1991}
1992
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001993bool OatWriter::WriteClassOffsets(OutputStream* out) {
1994 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1995 if (oat_dex_file.class_offsets_offset_ != 0u) {
1996 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1997 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1998 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1999 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
2000 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00002001 return false;
2002 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002003 if (!oat_dex_file.WriteClassOffsets(this, out)) {
2004 return false;
2005 }
2006 }
2007 }
2008 return true;
2009}
2010
2011bool OatWriter::WriteClasses(OutputStream* out) {
2012 for (OatClass& oat_class : oat_classes_) {
2013 if (!oat_class.Write(this, out, oat_data_offset_)) {
2014 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
2015 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00002016 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002017 }
2018 return true;
2019}
2020
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002021size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002022 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002023 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2024 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2025 return 0;
2026 }
2027 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002028 size_vmap_table_ = relative_offset - vmap_tables_offset;
2029
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002030 return relative_offset;
2031}
2032
2033size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002034 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002035 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002036
Ian Rogers848871b2013-08-05 10:56:33 -07002037 #define DO_TRAMPOLINE(field) \
2038 do { \
2039 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2040 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002041 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002042 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002043 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002044 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002045 return false; \
2046 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002047 size_ ## field += (field)->size(); \
2048 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002049 DCHECK_OFFSET(); \
2050 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002051
Ian Rogers848871b2013-08-05 10:56:33 -07002052 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002053 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002054 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002055 DO_TRAMPOLINE(quick_resolution_trampoline_);
2056 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2057 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002058 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002059 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002060}
2061
Ian Rogers3d504072014-03-01 09:16:49 -08002062size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002063 const size_t file_offset,
2064 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002065 #define VISIT(VisitorType) \
2066 do { \
2067 VisitorType visitor(this, out, file_offset, relative_offset); \
2068 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2069 return 0; \
2070 } \
2071 relative_offset = visitor.GetOffset(); \
2072 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002073
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002074 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002075
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002076 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002077
Vladimir Markob163bb72015-03-31 21:49:49 +01002078 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2079 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2080 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2081
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002082 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002083}
2084
Vladimir Marko944da602016-02-19 12:27:55 +00002085bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002086 // Get the elf file offset of the oat file.
2087 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2088 if (raw_file_offset == static_cast<off_t>(-1)) {
2089 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2090 return false;
2091 }
2092 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2093 return true;
2094}
2095
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002096bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2097 // Read the dex file header and perform minimal verification.
2098 uint8_t raw_header[sizeof(DexFile::Header)];
2099 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2100 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2101 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2102 return false;
2103 }
2104 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2105 return false;
2106 }
2107
2108 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2109 oat_dex_file->dex_file_size_ = header->file_size_;
2110 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2111 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2112 return true;
2113}
2114
2115bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2116 if (!DexFile::IsMagicValid(raw_header)) {
2117 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2118 return false;
2119 }
2120 if (!DexFile::IsVersionValid(raw_header)) {
2121 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2122 return false;
2123 }
2124 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2125 if (header->file_size_ < sizeof(DexFile::Header)) {
2126 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2127 << " File: " << location;
2128 return false;
2129 }
2130 return true;
2131}
2132
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002133bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002134 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002135
David Brazdil7b49e6c2016-09-01 11:06:18 +01002136 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002137
2138 // Write dex files.
2139 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002140 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002141 return false;
2142 }
2143 }
2144
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002145 CloseSources();
2146 return true;
2147}
2148
2149void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002150 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2151 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2152 }
2153 zipped_dex_files_.clear();
2154 zip_archives_.clear();
2155 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002156}
2157
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002158bool OatWriter::WriteDexFile(OutputStream* out,
2159 File* file,
2160 OatDexFile* oat_dex_file,
2161 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002162 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002163 return false;
2164 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002165 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002166 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002167 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2168 return false;
2169 }
2170 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002171 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002172 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002173 return false;
2174 }
2175 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002176 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002177 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002178 return false;
2179 }
2180 } else {
2181 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002182 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002183 return false;
2184 }
2185 }
2186
2187 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002188 if (kIsVdexEnabled) {
2189 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2190 vdex_size_ += oat_dex_file->dex_file_size_;
2191 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002192 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002193 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2194 oat_size_ += oat_dex_file->dex_file_size_;
2195 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002196 size_dex_file_ += oat_dex_file->dex_file_size_;
2197 return true;
2198}
2199
2200bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2201 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002202 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2203 size_t start_offset = RoundUp(initial_offset, 4);
2204 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2205 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002206
2207 // Seek to the start of the dex file and flush any pending operations in the stream.
2208 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002209 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2210 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002211 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002212 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002213 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2214 return false;
2215 }
2216 if (!out->Flush()) {
2217 PLOG(ERROR) << "Failed to flush before writing dex file."
2218 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2219 return false;
2220 }
2221 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002222 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002223 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002224 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002225 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2226 return false;
2227 }
2228
David Brazdil7b49e6c2016-09-01 11:06:18 +01002229 if (kIsVdexEnabled) {
2230 vdex_size_ = start_offset;
2231 } else {
2232 oat_size_ = start_offset;
2233 }
2234 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002235 return true;
2236}
2237
Jeff Hao608f2ce2016-10-19 11:17:11 -07002238bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2239 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2240 std::string error_msg;
2241 std::string location(oat_dex_file->GetLocation());
2242 std::unique_ptr<const DexFile> dex_file;
2243 if (oat_dex_file->source_.IsZipEntry()) {
2244 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2245 std::unique_ptr<MemMap> mem_map(
2246 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2247 dex_file = DexFile::Open(location,
2248 zip_entry->GetCrc32(),
2249 std::move(mem_map),
2250 /* verify */ true,
2251 /* verify_checksum */ true,
2252 &error_msg);
2253 } else {
2254 DCHECK(oat_dex_file->source_.IsRawFile());
2255 File* raw_file = oat_dex_file->source_.GetRawFile();
2256 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2257 }
2258 Options options;
2259 options.output_to_memmap_ = true;
2260 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2261 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2262 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002263 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002264 return false;
2265 }
2266 // Set the checksum of the new oat dex file to be the original file's checksum.
2267 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2268 return true;
2269}
2270
David Brazdil7b49e6c2016-09-01 11:06:18 +01002271bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002272 File* file,
2273 OatDexFile* oat_dex_file,
2274 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002275 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2276 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002277
2278 // Extract the dex file and get the extracted size.
2279 std::string error_msg;
2280 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2281 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2282 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2283 return false;
2284 }
2285 if (file->Flush() != 0) {
2286 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2287 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2288 return false;
2289 }
2290 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2291 if (extracted_end == static_cast<off_t>(-1)) {
2292 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2293 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2294 return false;
2295 }
2296 if (extracted_end < static_cast<off_t>(start_offset)) {
2297 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2298 << " Start: " << start_offset
2299 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2300 return false;
2301 }
2302 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2303 if (extracted_size < sizeof(DexFile::Header)) {
2304 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2305 << extracted_size << " File: " << oat_dex_file->GetLocation();
2306 return false;
2307 }
2308
2309 // Read the dex file header and extract required data to OatDexFile.
2310 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2311 if (actual_offset != static_cast<off_t>(start_offset)) {
2312 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2313 << " Expected: " << start_offset
2314 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2315 return false;
2316 }
2317 if (!ReadDexFileHeader(file, oat_dex_file)) {
2318 return false;
2319 }
2320 if (extracted_size < oat_dex_file->dex_file_size_) {
2321 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2322 << " file size from header: " << oat_dex_file->dex_file_size_
2323 << " File: " << oat_dex_file->GetLocation();
2324 return false;
2325 }
2326
2327 // Override the checksum from header with the CRC from ZIP entry.
2328 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2329
2330 // Seek both file and stream to the end offset.
2331 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2332 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2333 if (actual_offset != static_cast<off_t>(end_offset)) {
2334 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2335 << " Expected: " << end_offset
2336 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2337 return false;
2338 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002339 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002340 if (actual_offset != static_cast<off_t>(end_offset)) {
2341 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2342 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2343 return false;
2344 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002345 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002346 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2347 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2348 return false;
2349 }
2350
2351 // If we extracted more than the size specified in the header, truncate the file.
2352 if (extracted_size > oat_dex_file->dex_file_size_) {
2353 if (file->SetLength(end_offset) != 0) {
2354 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002355 << " File: " << oat_dex_file->GetLocation()
2356 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002357 return false;
2358 }
2359 }
2360
2361 return true;
2362}
2363
David Brazdil7b49e6c2016-09-01 11:06:18 +01002364bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002365 File* file,
2366 OatDexFile* oat_dex_file,
2367 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002368 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2369 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002370
2371 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2372 if (input_offset != static_cast<off_t>(0)) {
2373 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2374 << " Expected: 0"
2375 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2376 return false;
2377 }
2378 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2379 return false;
2380 }
2381
2382 // Copy the input dex file using sendfile().
2383 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2384 PLOG(ERROR) << "Failed to copy dex file to oat file."
2385 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2386 return false;
2387 }
2388 if (file->Flush() != 0) {
2389 PLOG(ERROR) << "Failed to flush dex file."
2390 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2391 return false;
2392 }
2393
2394 // Check file position and seek the stream to the end offset.
2395 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2396 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2397 if (actual_offset != static_cast<off_t>(end_offset)) {
2398 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2399 << " Expected: " << end_offset
2400 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2401 return false;
2402 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002403 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002404 if (actual_offset != static_cast<off_t>(end_offset)) {
2405 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2406 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2407 return false;
2408 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002409 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002410 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2411 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2412 return false;
2413 }
2414
2415 return true;
2416}
2417
David Brazdil7b49e6c2016-09-01 11:06:18 +01002418bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002419 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002420 const uint8_t* dex_file,
2421 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002422 // Note: The raw data has already been checked to contain the header
2423 // and all the data that the header specifies as the file size.
2424 DCHECK(dex_file != nullptr);
2425 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2426 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2427
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002428 if (update_input_vdex) {
2429 // The vdex already contains the dex code, no need to write it again.
2430 } else {
2431 if (!out->WriteFully(dex_file, header->file_size_)) {
2432 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2433 << " to " << out->GetLocation();
2434 return false;
2435 }
2436 if (!out->Flush()) {
2437 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2438 << " File: " << oat_dex_file->GetLocation();
2439 return false;
2440 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002441 }
2442
2443 // Update dex file size and resize class offsets in the OatDexFile.
2444 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002445 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002446 oat_dex_file->dex_file_size_ = header->file_size_;
2447 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2448 return true;
2449}
2450
2451bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2452 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2453
David Brazdil181e1cc2016-09-01 16:38:47 +00002454 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2455 if (initial_offset == static_cast<off_t>(-1)) {
2456 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2457 return false;
2458 }
2459
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002460 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2461 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2462 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2463 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2464 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2465 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2466 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2467 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2468 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2469 return false;
2470 }
2471
2472 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2473 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2474
2475 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2476 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2477
2478 // Write OatDexFile.
2479 if (!oat_dex_file->Write(this, rodata)) {
2480 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2481 return false;
2482 }
2483 }
2484
David Brazdil181e1cc2016-09-01 16:38:47 +00002485 // Seek back to the initial position.
2486 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2487 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2488 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2489 return false;
2490 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002491
David Brazdilb92ba622016-09-01 16:00:30 +00002492 return true;
2493}
2494
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002495bool OatWriter::OpenDexFiles(
2496 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002497 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002498 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2499 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2500 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2501
2502 if (oat_dex_files_.empty()) {
2503 // Nothing to do.
2504 return true;
2505 }
2506
2507 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002508 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2509
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002510 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002511 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2512 length,
2513 PROT_READ | PROT_WRITE,
2514 MAP_SHARED,
2515 file->Fd(),
2516 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2517 /* low_4gb */ false,
2518 file->GetPath().c_str(),
2519 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002520 if (dex_files_map == nullptr) {
2521 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2522 << " error: " << error_msg;
2523 return false;
2524 }
2525 std::vector<std::unique_ptr<const DexFile>> dex_files;
2526 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2527 // Make sure no one messed with input files while we were copying data.
2528 // At the very least we need consistent file size and number of class definitions.
2529 const uint8_t* raw_dex_file =
2530 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2531 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2532 // Note: ValidateDexFileHeader() already logged an error message.
2533 LOG(ERROR) << "Failed to verify written dex file header!"
2534 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2535 << " ~ " << static_cast<const void*>(raw_dex_file);
2536 return false;
2537 }
2538 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2539 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2540 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2541 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2542 << " Output: " << file->GetPath();
2543 return false;
2544 }
2545 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2546 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2547 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2548 << " Output: " << file->GetPath();
2549 return false;
2550 }
2551
2552 // Now, open the dex file.
2553 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2554 oat_dex_file.dex_file_size_,
2555 oat_dex_file.GetLocation(),
2556 oat_dex_file.dex_file_location_checksum_,
2557 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002558 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002559 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002560 &error_msg));
2561 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002562 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2563 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002564 return false;
2565 }
2566 }
2567
2568 *opened_dex_files_map = std::move(dex_files_map);
2569 *opened_dex_files = std::move(dex_files);
2570 return true;
2571}
2572
2573bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002574 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002575 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2576 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2577
David Brazdil7b49e6c2016-09-01 11:06:18 +01002578 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2579 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2580 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2581 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2582 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2583 return false;
2584 }
2585
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002586 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2587 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2588 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002589 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2590
2591 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2592 oat_dex_file->class_offsets_.empty()) {
2593 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002594 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002595
2596 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2597 if (table_size == 0u) {
2598 continue;
2599 }
2600
2601 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002602 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002603 const DexFile& dex_file = *opened_dex_files[i];
2604 {
2605 std::unique_ptr<TypeLookupTable> type_lookup_table =
2606 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2607 type_lookup_table_oat_dex_files_.push_back(
2608 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2609 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2610 }
2611 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002612
2613 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002614 size_t initial_offset = oat_size_;
2615 size_t rodata_offset = RoundUp(initial_offset, 4);
2616 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002617
2618 if (padding_size != 0u) {
2619 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002620 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002621 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2622 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002623 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002624 return false;
2625 }
2626 }
2627
2628 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002629 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002630 DCHECK_EQ(table_size, table->RawDataLength());
2631
David Brazdil7b49e6c2016-09-01 11:06:18 +01002632 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002633 PLOG(ERROR) << "Failed to write lookup table."
2634 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002635 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002636 return false;
2637 }
2638
2639 oat_dex_file->lookup_table_offset_ = rodata_offset;
2640
David Brazdil7b49e6c2016-09-01 11:06:18 +01002641 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002642 size_oat_lookup_table_ += table_size;
2643 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002644 }
2645
David Brazdil7b49e6c2016-09-01 11:06:18 +01002646 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002647 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002648 << " File: " << oat_rodata->GetLocation();
2649 return false;
2650 }
2651
2652 return true;
2653}
2654
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002655bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002656 if (!kIsVdexEnabled) {
2657 return true;
2658 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002659 // Write checksums
2660 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2661 if (actual_offset != sizeof(VdexFile::Header)) {
2662 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2663 << " File: " << vdex_out->GetLocation();
2664 return false;
2665 }
2666
2667 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2668 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2669 if (!vdex_out->WriteFully(
2670 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2671 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2672 << vdex_out->GetLocation();
2673 return false;
2674 }
2675 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2676 }
2677
2678 // Write header.
2679 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002680 if (actual_offset != 0) {
2681 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2682 << " File: " << vdex_out->GetLocation();
2683 return false;
2684 }
2685
David Brazdil5d5a36b2016-09-14 15:34:10 +01002686 DCHECK_NE(vdex_dex_files_offset_, 0u);
2687 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2688
2689 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002690 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2691 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002692
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002693 VdexFile::Header vdex_header(oat_dex_files_.size(),
2694 dex_section_size,
2695 verifier_deps_section_size,
2696 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002697 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2698 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002699 return false;
2700 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002701 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002702
David Brazdil5d5a36b2016-09-14 15:34:10 +01002703 if (!vdex_out->Flush()) {
2704 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2705 << " File: " << vdex_out->GetLocation();
2706 return false;
2707 }
2708
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002709 return true;
2710}
2711
Vladimir Markof4da6752014-08-01 19:04:18 +01002712bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2713 static const uint8_t kPadding[] = {
2714 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2715 };
2716 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002717 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002718 return false;
2719 }
2720 size_code_alignment_ += aligned_code_delta;
2721 return true;
2722}
2723
Vladimir Marko944da602016-02-19 12:27:55 +00002724void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2725 DCHECK(dex_files_ != nullptr);
2726 DCHECK(relative_patcher_ != nullptr);
2727 DCHECK_NE(oat_data_offset_, 0u);
2728 if (image_writer_ != nullptr && !dex_files_->empty()) {
2729 // The oat data begin may not be initialized yet but the oat file offset is ready.
2730 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2731 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2732 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002733 }
2734}
2735
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002736OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2737 DexFileSource source,
2738 CreateTypeLookupTable create_type_lookup_table)
2739 : source_(source),
2740 create_type_lookup_table_(create_type_lookup_table),
2741 dex_file_size_(0),
2742 offset_(0),
2743 dex_file_location_size_(strlen(dex_file_location)),
2744 dex_file_location_data_(dex_file_location),
2745 dex_file_location_checksum_(0u),
2746 dex_file_offset_(0u),
2747 class_offsets_offset_(0u),
2748 lookup_table_offset_(0u),
2749 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002750}
2751
2752size_t OatWriter::OatDexFile::SizeOf() const {
2753 return sizeof(dex_file_location_size_)
2754 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002755 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002756 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002757 + sizeof(class_offsets_offset_)
2758 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002759}
2760
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002761void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2762 DCHECK_EQ(class_offsets_offset_, 0u);
2763 if (!class_offsets_.empty()) {
2764 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002765 size_t initial_offset = oat_writer->oat_size_;
2766 size_t offset = RoundUp(initial_offset, 4);
2767 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002768 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002769 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002770 }
2771}
2772
2773bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2774 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002775 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002776
Vladimir Markoe079e212016-05-25 12:49:49 +01002777 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002778 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002779 return false;
2780 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002781 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002782
Vladimir Markoe079e212016-05-25 12:49:49 +01002783 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002784 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002785 return false;
2786 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002787 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002788
Vladimir Markoe079e212016-05-25 12:49:49 +01002789 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002790 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002791 return false;
2792 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002793 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002794
Vladimir Markoe079e212016-05-25 12:49:49 +01002795 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002796 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002797 return false;
2798 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002799 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002800
Vladimir Markoe079e212016-05-25 12:49:49 +01002801 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002802 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2803 return false;
2804 }
2805 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2806
Vladimir Markoe079e212016-05-25 12:49:49 +01002807 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002808 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2809 return false;
2810 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002811 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002812
2813 return true;
2814}
2815
2816bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002817 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002818 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2819 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002820 return false;
2821 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002822 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002823 return true;
2824}
2825
Brian Carlstromba150c32013-08-27 17:31:03 -07002826OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002827 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002828 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002829 mirror::Class::Status status)
2830 : compiled_methods_(compiled_methods) {
2831 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002832 CHECK_LE(num_non_null_compiled_methods, num_methods);
2833
Brian Carlstrom265091e2013-01-30 14:08:26 -08002834 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002835 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2836
2837 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2838 // apply when there are 0 methods, we just arbitrarily say that 0
2839 // methods means kOatClassNoneCompiled and that we won't use
2840 // kOatClassAllCompiled unless there is at least one compiled
2841 // method. This means in an interpretter only system, we can assert
2842 // that all classes are kOatClassNoneCompiled.
2843 if (num_non_null_compiled_methods == 0) {
2844 type_ = kOatClassNoneCompiled;
2845 } else if (num_non_null_compiled_methods == num_methods) {
2846 type_ = kOatClassAllCompiled;
2847 } else {
2848 type_ = kOatClassSomeCompiled;
2849 }
2850
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002851 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002852 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002853 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002854
2855 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2856 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002857 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002858 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2859 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2860 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2861 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002862 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002863 method_bitmap_size_ = 0;
2864 }
2865
2866 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002867 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002868 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002869 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2870 } else {
2871 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2872 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2873 if (type_ == kOatClassSomeCompiled) {
2874 method_bitmap_->SetBit(i);
2875 }
2876 }
2877 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002878}
2879
Brian Carlstrom265091e2013-01-30 14:08:26 -08002880size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2881 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002882 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2883 if (method_offset == 0) {
2884 return 0;
2885 }
2886 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002887}
2888
2889size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2890 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002891 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002892}
2893
2894size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002895 return sizeof(status_)
2896 + sizeof(type_)
2897 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2898 + method_bitmap_size_
2899 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002900}
2901
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002902bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002903 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002904 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002905 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002906 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002907 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002908 return false;
2909 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002910 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002911
Vladimir Markoe079e212016-05-25 12:49:49 +01002912 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002913 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002914 return false;
2915 }
2916 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002917
Brian Carlstromba150c32013-08-27 17:31:03 -07002918 if (method_bitmap_size_ != 0) {
2919 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002920 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002921 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002922 return false;
2923 }
2924 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002925
Vladimir Markoe079e212016-05-25 12:49:49 +01002926 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002927 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002928 return false;
2929 }
2930 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2931 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002932
Vladimir Markoe079e212016-05-25 12:49:49 +01002933 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002934 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002935 return false;
2936 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002937 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002938 return true;
2939}
2940
Brian Carlstrome24fa612011-09-29 00:53:55 -07002941} // namespace art