blob: bd2c5e3bfcdd173e22258783663d28f4d75da5cf [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
Vladimir Marko1998cd02017-01-13 13:02:58 +0000589 {
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)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000719 // The oat class status is used only for verification of resolved classes,
720 // so use kStatusErrorResolved whether the class was resolved or unresolved
721 // during compile-time verification.
722 status = mirror::Class::kStatusErrorResolved;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723 } else {
724 status = mirror::Class::kStatusNotReady;
725 }
726
Vladimir Marko49b0f452015-12-10 13:49:19 +0000727 writer_->oat_classes_.emplace_back(offset_,
728 compiled_methods_,
729 num_non_null_compiled_methods_,
730 status);
731 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100732 return DexMethodVisitor::EndClass();
733 }
734
735 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000736 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100737 size_t num_non_null_compiled_methods_;
738};
739
740class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
741 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100742 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100743 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100744 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
745 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100746 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100747 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
748 }
749
750 bool EndClass() {
751 OatDexMethodVisitor::EndClass();
752 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100753 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100754 }
755 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100756 }
757
758 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700759 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000760 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100761 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
762
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100763 if (it.GetMethodCodeItem() != nullptr) {
764 current_quickening_info_offset_ += sizeof(uint32_t);
765 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100766 if (compiled_method != nullptr) {
767 // Derived from CompiledMethod.
768 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100769
Vladimir Marko35831e82015-09-11 11:59:18 +0100770 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
771 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800772 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800773
David Srbecky009e2a62015-04-15 02:46:30 +0100774 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100775 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800776 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000777 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000778 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
779 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800780 // Duplicate methods, we want the same code for both of them so that the oat writer puts
781 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800782 } else {
783 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100784 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800785 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000786 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100787 quick_code_offset = dedupe_map_.GetOrCreate(
788 compiled_method,
789 [this, &deduped, compiled_method, &it, thumb_offset]() {
790 deduped = false;
791 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
792 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800793 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100795 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000796 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100797 // TODO: Should this be a hard failure?
798 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700799 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000800 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
801 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100802 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000803 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100804 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800805 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 // Update quick method header.
808 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
809 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700810 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800811 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
812 // to 0-offset and we need to adjust it by code_offset.
813 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100814 if (!compiled_method->GetQuickCode().empty()) {
815 // If the code is compiled, we write the offset of the stack map relative
816 // to the code,
817 if (vmap_table_offset != 0u) {
818 vmap_table_offset += code_offset;
819 DCHECK_LT(vmap_table_offset, code_offset);
820 }
821 } else {
822 if (kIsVdexEnabled) {
823 // We write the offset in the .vdex file.
824 DCHECK_EQ(vmap_table_offset, 0u);
825 vmap_table_offset = current_quickening_info_offset_;
826 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
827 current_quickening_info_offset_ += map.size() * sizeof(map.front());
828 } else {
829 // We write the offset of the quickening info relative to the code.
830 vmap_table_offset += code_offset;
831 DCHECK_LT(vmap_table_offset, code_offset);
832 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800833 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800834 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
835 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
836 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100837 *method_header = OatQuickMethodHeader(vmap_table_offset,
838 frame_size_in_bytes,
839 core_spill_mask,
840 fp_spill_mask,
841 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100842
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000843 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800844 // Update offsets. (Checksum is updated when writing.)
845 offset_ += sizeof(*method_header); // Method header is prepended before code.
846 offset_ += code_size;
847 // Record absolute patch locations.
848 if (!compiled_method->GetPatches().empty()) {
849 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
850 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000851 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100852 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100853 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000854 if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
855 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
856 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
857 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000858 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
859 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
860 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
861 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100862 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100863 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800864 }
Alex Light78382fa2014-06-06 15:45:32 -0700865
David Srbecky91cc06c2016-03-07 16:13:58 +0000866 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000867 // Exclude quickened dex methods (code_size == 0) since they have no native code.
868 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
869 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800870 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000871 debug::MethodDebugInfo info = debug::MethodDebugInfo();
872 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000873 info.dex_file = dex_file_;
874 info.class_def_index = class_def_index_;
875 info.dex_method_index = it.GetMemberIndex();
876 info.access_flags = it.GetMethodAccessFlags();
877 info.code_item = it.GetMethodCodeItem();
878 info.isa = compiled_method->GetInstructionSet();
879 info.deduped = deduped;
880 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
881 info.is_optimized = method_header->IsOptimized();
882 info.is_code_address_text_relative = true;
883 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
884 info.code_size = code_size;
885 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
886 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
887 info.cfi = compiled_method->GetCFIInfo();
888 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100889 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100890
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100891 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
892 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
893 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100894 ++method_offsets_index_;
895 }
896
897 return true;
898 }
899
900 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000901 struct CodeOffsetsKeyComparator {
902 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100903 // Code is deduplicated by CompilerDriver, compare only data pointers.
904 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
905 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000906 }
907 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100908 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
909 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000910 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100911 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
912 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000913 }
914 return false;
915 }
916 };
917
David Srbecky009e2a62015-04-15 02:46:30 +0100918 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
919 const ClassDataItemIterator& it,
920 uint32_t thumb_offset) {
921 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100922 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100923 offset_ += CodeAlignmentSize(offset_, *compiled_method);
924 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100925 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
926 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
927 }
928
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100929 // Deduplication is already done on a pointer basis by the compiler driver,
930 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100931 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100932
David Srbecky009e2a62015-04-15 02:46:30 +0100933 // Cache of compiler's --debuggable option.
934 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100935
936 // Offset in the vdex file for the quickening info.
937 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100938};
939
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100940class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
941 public:
942 InitMapMethodVisitor(OatWriter* writer, size_t offset)
943 : OatDexMethodVisitor(writer, offset) {
944 }
945
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700946 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700947 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000948 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100949 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
950
951 if (compiled_method != nullptr) {
952 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100953 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
954 // be in the vdex file.
955 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700956 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100957
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100958 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
959 uint32_t map_size = map.size() * sizeof(map[0]);
960 if (map_size != 0u) {
961 size_t offset = dedupe_map_.GetOrCreate(
962 map.data(),
963 [this, map_size]() {
964 uint32_t new_offset = offset_;
965 offset_ += map_size;
966 return new_offset;
967 });
968 // Code offset is not initialized yet, so set the map offset to 0u-offset.
969 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700970 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100971 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100972 }
973 ++method_offsets_index_;
974 }
975
976 return true;
977 }
978
979 private:
980 // Deduplication is already done on a pointer basis by the compiler driver,
981 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100982 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100983};
984
985class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
986 public:
987 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800988 : OatDexMethodVisitor(writer, offset),
989 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100990 }
991
992 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700993 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800994 const DexFile::TypeId& type_id =
995 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
996 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
997 // Skip methods that are not in the image.
998 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
999 return true;
1000 }
1001
Vladimir Marko49b0f452015-12-10 13:49:19 +00001002 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001003 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1004
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001005 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001006 if (compiled_method != nullptr) {
1007 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1008 offsets = oat_class->method_offsets_[method_offsets_index_];
1009 ++method_offsets_index_;
1010 }
1011
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001012 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001013 // Unchecked as we hold mutator_lock_ on entry.
1014 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001015 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001016 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
1017 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001018 ArtMethod* method;
1019 if (writer_->HasBootImage()) {
1020 const InvokeType invoke_type = it.GetMethodInvokeType(
1021 dex_file_->GetClassDef(class_def_index_));
1022 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1023 *dex_file_,
1024 it.GetMemberIndex(),
1025 dex_cache,
1026 ScopedNullHandle<mirror::ClassLoader>(),
1027 nullptr,
1028 invoke_type);
1029 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001030 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001031 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001032 soa.Self()->AssertPendingException();
1033 mirror::Throwable* exc = soa.Self()->GetException();
1034 std::string dump = exc->Dump();
1035 LOG(FATAL) << dump;
1036 UNREACHABLE();
1037 }
1038 } else {
1039 // Should already have been resolved by the compiler, just peek into the dex cache.
1040 // It may not be resolved if the class failed to verify, in this case, don't set the
1041 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1042 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001043 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001044 if (method != nullptr &&
1045 compiled_method != nullptr &&
1046 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001047 method->SetEntryPointFromQuickCompiledCodePtrSize(
1048 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1049 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001050
1051 return true;
1052 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001053
1054 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001055 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001056};
1057
1058class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1059 public:
1060 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001061 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001062 : OatDexMethodVisitor(writer, relative_offset),
1063 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001064 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001065 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001066 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001067 class_linker_(Runtime::Current()->GetClassLinker()),
1068 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001069 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001070 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001071 // If we're creating the image, the address space must be ready so that we can apply patches.
1072 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001073 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001074 }
1075
Vladimir Markof4da6752014-08-01 19:04:18 +01001076 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001077 }
1078
1079 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001080 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001081 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1082 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001083 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001084 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001085 }
1086 return true;
1087 }
1088
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001089 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001090 bool result = OatDexMethodVisitor::EndClass();
1091 if (oat_class_index_ == writer_->oat_classes_.size()) {
1092 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001093 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001094 if (UNLIKELY(offset_ == 0u)) {
1095 PLOG(ERROR) << "Failed to write final relative call thunks";
1096 result = false;
1097 }
1098 }
1099 return result;
1100 }
1101
1102 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001103 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001104 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001105 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1106
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001107 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001108 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001109 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001110 size_t file_offset = file_offset_;
1111 OutputStream* out = out_;
1112
Vladimir Marko35831e82015-09-11 11:59:18 +01001113 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1114 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001115
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001116 // Deduplicate code arrays.
1117 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1118 if (method_offsets.code_offset_ > offset_) {
1119 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1120 if (offset_ == 0u) {
1121 ReportWriteFailure("relative call thunk", it);
1122 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001123 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001124 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1125 if (alignment_size != 0) {
1126 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001127 ReportWriteFailure("code alignment padding", it);
1128 return false;
1129 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001130 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001131 DCHECK_OFFSET_();
1132 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001133 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001134 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1135 DCHECK_EQ(method_offsets.code_offset_,
1136 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001137 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001138 const OatQuickMethodHeader& method_header =
1139 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001140 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001141 ReportWriteFailure("method header", it);
1142 return false;
1143 }
1144 writer_->size_method_header_ += sizeof(method_header);
1145 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001146 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001147
1148 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001149 patched_code_.assign(quick_code.begin(), quick_code.end());
1150 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001151 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001152 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001153 switch (patch.GetType()) {
1154 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001155 // NOTE: Relative calls across oat files are not supported.
1156 uint32_t target_offset = GetTargetOffset(patch);
1157 writer_->relative_patcher_->PatchCall(&patched_code_,
1158 literal_offset,
1159 offset_ + literal_offset,
1160 target_offset);
1161 break;
1162 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001163 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001164 uint32_t target_offset = GetDexCacheOffset(patch);
1165 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1166 patch,
1167 offset_ + literal_offset,
1168 target_offset);
1169 break;
1170 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001171 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001172 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1173 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1174 patch,
1175 offset_ + literal_offset,
1176 target_offset);
1177 break;
1178 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001179 case LinkerPatch::Type::kStringBssEntry: {
1180 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1181 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1182 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1183 patch,
1184 offset_ + literal_offset,
1185 target_offset);
1186 break;
1187 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001188 case LinkerPatch::Type::kTypeRelative: {
1189 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1190 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1191 patch,
1192 offset_ + literal_offset,
1193 target_offset);
1194 break;
1195 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001196 case LinkerPatch::Type::kTypeBssEntry: {
1197 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1198 uint32_t target_offset = writer_->bss_type_entries_.Get(ref);
1199 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1200 patch,
1201 offset_ + literal_offset,
1202 target_offset);
1203 break;
1204 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001205 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001206 uint32_t target_offset = GetTargetOffset(patch);
1207 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1208 break;
1209 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001210 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001211 ArtMethod* method = GetTargetMethod(patch);
1212 PatchMethodAddress(&patched_code_, literal_offset, method);
1213 break;
1214 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001215 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001216 mirror::String* string = GetTargetString(patch);
1217 PatchObjectAddress(&patched_code_, literal_offset, string);
1218 break;
1219 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001220 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001221 mirror::Class* type = GetTargetType(patch);
1222 PatchObjectAddress(&patched_code_, literal_offset, type);
1223 break;
1224 }
1225 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001226 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001227 break;
1228 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001229 }
1230 }
1231 }
1232
Vladimir Markoe079e212016-05-25 12:49:49 +01001233 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001234 ReportWriteFailure("method code", it);
1235 return false;
1236 }
1237 writer_->size_code_ += code_size;
1238 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001239 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001240 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001241 ++method_offsets_index_;
1242 }
1243
1244 return true;
1245 }
1246
1247 private:
1248 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001249 const size_t file_offset_;
1250 const ScopedObjectAccess soa_;
1251 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001252 ClassLinker* const class_linker_;
1253 mirror::DexCache* dex_cache_;
1254 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001255
1256 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1257 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001258 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001259 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001260
Mathieu Chartiere401d142015-04-22 13:56:20 -07001261 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001262 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001263 MethodReference ref = patch.TargetMethod();
1264 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001265 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1266 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001267 ArtMethod* method = dex_cache->GetResolvedMethod(
1268 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001269 CHECK(method != nullptr);
1270 return method;
1271 }
1272
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001273 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001274 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1275 // If there's no new compiled code, either we're compiling an app and the target method
1276 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001277 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001278 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001279 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001280 PointerSize size =
1281 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001282 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1283 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001284 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001285 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1286 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1287 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1288 target_offset = PointerToLowMemUInt32(oat_code_offset);
1289 } else {
1290 target_offset = target->IsNative()
1291 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1292 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1293 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001294 }
1295 return target_offset;
1296 }
1297
Vladimir Marko052164a2016-04-27 13:54:18 +01001298 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001299 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001300 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001301 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001302 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1303 }
1304
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001305 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001306 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001307 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1308 CHECK(type != nullptr);
1309 return type;
1310 }
1311
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001312 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001313 ScopedObjectAccessUnchecked soa(Thread::Current());
1314 StackHandleScope<1> hs(soa.Self());
1315 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1316 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1317 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1318 patch.TargetStringIndex(),
1319 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001320 DCHECK(string != nullptr);
1321 DCHECK(writer_->HasBootImage() ||
1322 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1323 return string;
1324 }
1325
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001326 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001327 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001328 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1329 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1330 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1331 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001332 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001333 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001334 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1335 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001336 }
1337 }
1338
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001339 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001340 DCHECK(writer_->HasBootImage());
1341 object = writer_->image_writer_->GetImageAddress(object);
1342 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1343 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1344 // TODO: Clean up offset types. The target offset must be treated as signed.
1345 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1346 }
1347
Vladimir Markof4da6752014-08-01 19:04:18 +01001348 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001349 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001350 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001351 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001352 } else {
1353 // NOTE: We're using linker patches for app->boot references when the image can
1354 // be relocated and therefore we need to emit .oat_patches. We're not using this
1355 // for app->app references, so check that the object is in the image space.
1356 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001357 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001358 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001359 uint32_t address = PointerToLowMemUInt32(object);
1360 DCHECK_LE(offset + 4, code->size());
1361 uint8_t* data = &(*code)[offset];
1362 data[0] = address & 0xffu;
1363 data[1] = (address >> 8) & 0xffu;
1364 data[2] = (address >> 16) & 0xffu;
1365 data[3] = (address >> 24) & 0xffu;
1366 }
1367
Mathieu Chartiere401d142015-04-22 13:56:20 -07001368 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001369 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001370 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001371 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001372 } else if (kIsDebugBuild) {
1373 // NOTE: We're using linker patches for app->boot references when the image can
1374 // be relocated and therefore we need to emit .oat_patches. We're not using this
1375 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001376 std::vector<gc::space::ImageSpace*> image_spaces =
1377 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1378 bool contains_method = false;
1379 for (gc::space::ImageSpace* image_space : image_spaces) {
1380 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1381 contains_method |=
1382 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1383 }
1384 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001385 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001386 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001387 uint32_t address = PointerToLowMemUInt32(method);
1388 DCHECK_LE(offset + 4, code->size());
1389 uint8_t* data = &(*code)[offset];
1390 data[0] = address & 0xffu;
1391 data[1] = (address >> 8) & 0xffu;
1392 data[2] = (address >> 16) & 0xffu;
1393 data[3] = (address >> 24) & 0xffu;
1394 }
1395
Vladimir Markof4da6752014-08-01 19:04:18 +01001396 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001397 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001398 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001399 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001400 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1401 // TODO: Clean up offset types.
1402 // The target_offset must be treated as signed for cross-oat patching.
1403 const void* target = reinterpret_cast<const void*>(
1404 writer_->image_writer_->GetOatDataBegin(oat_index) +
1405 static_cast<int32_t>(target_offset));
1406 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001407 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001408 DCHECK_LE(offset + 4, code->size());
1409 uint8_t* data = &(*code)[offset];
1410 data[0] = address & 0xffu;
1411 data[1] = (address >> 8) & 0xffu;
1412 data[2] = (address >> 16) & 0xffu;
1413 data[3] = (address >> 24) & 0xffu;
1414 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001415};
1416
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001417class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1418 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001419 WriteMapMethodVisitor(OatWriter* writer,
1420 OutputStream* out,
1421 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001422 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 : OatDexMethodVisitor(writer, relative_offset),
1424 out_(out),
1425 file_offset_(file_offset) {
1426 }
1427
1428 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001429 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001430 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1431
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001432 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001433 size_t file_offset = file_offset_;
1434 OutputStream* out = out_;
1435
Mingyao Yang063fc772016-08-02 11:02:54 -07001436 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001437 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001438 ++method_offsets_index_;
1439
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001440 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1441 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1442 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001443 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001444
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001445 // If vdex is enabled, only emit the map for compiled code. The quickening info
1446 // is emitted in the vdex already.
1447 if (map_offset != 0u &&
1448 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001449 // Transform map_offset to actual oat data offset.
1450 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1451 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001452 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001453
1454 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1455 size_t map_size = map.size() * sizeof(map[0]);
1456 if (map_offset == offset_) {
1457 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001458 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001459 ReportWriteFailure(it);
1460 return false;
1461 }
1462 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001463 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001464 }
1465 DCHECK_OFFSET_();
1466 }
1467
1468 return true;
1469 }
1470
1471 private:
1472 OutputStream* const out_;
1473 size_t const file_offset_;
1474
1475 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001476 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001477 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001478 }
1479};
1480
1481// Visit all methods from all classes in all dex files with the specified visitor.
1482bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1483 for (const DexFile* dex_file : *dex_files_) {
1484 const size_t class_def_count = dex_file->NumClassDefs();
1485 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1486 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1487 return false;
1488 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001489 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1490 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1491 const uint8_t* class_data = dex_file->GetClassData(class_def);
1492 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1493 ClassDataItemIterator it(*dex_file, class_data);
1494 while (it.HasNextStaticField()) {
1495 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001496 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001497 while (it.HasNextInstanceField()) {
1498 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001499 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001500 size_t class_def_method_index = 0u;
1501 while (it.HasNextDirectMethod()) {
1502 if (!visitor->VisitMethod(class_def_method_index, it)) {
1503 return false;
1504 }
1505 ++class_def_method_index;
1506 it.Next();
1507 }
1508 while (it.HasNextVirtualMethod()) {
1509 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1510 return false;
1511 }
1512 ++class_def_method_index;
1513 it.Next();
1514 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001515 }
1516 }
1517 if (UNLIKELY(!visitor->EndClass())) {
1518 return false;
1519 }
1520 }
1521 }
1522 return true;
1523}
1524
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001525size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1526 const InstructionSetFeatures* instruction_set_features,
1527 uint32_t num_dex_files,
1528 SafeMap<std::string, std::string>* key_value_store) {
1529 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1530 oat_header_.reset(OatHeader::Create(instruction_set,
1531 instruction_set_features,
1532 num_dex_files,
1533 key_value_store));
1534 size_oat_header_ += sizeof(OatHeader);
1535 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001536 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001537}
1538
1539size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001540 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1541 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001542 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001543 oat_dex_file.offset_ = offset;
1544 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001545 }
1546 return offset;
1547}
1548
Brian Carlstrom389efb02012-01-11 12:06:26 -08001549size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001550 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001551 InitOatClassesMethodVisitor visitor(this, offset);
1552 bool success = VisitDexMethods(&visitor);
1553 CHECK(success);
1554 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001555
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001556 // Update oat_dex_files_.
1557 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001558 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1559 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001560 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001561 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001562 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001563 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001564 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001565 CHECK(oat_class_it == oat_classes_.end());
1566
1567 return offset;
1568}
1569
1570size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001571 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1572 return offset;
1573 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001574 InitMapMethodVisitor visitor(this, offset);
1575 bool success = VisitDexMethods(&visitor);
1576 DCHECK(success);
1577 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001578
Brian Carlstrome24fa612011-09-29 00:53:55 -07001579 return offset;
1580}
1581
1582size_t OatWriter::InitOatCode(size_t offset) {
1583 // calculate the offsets within OatHeader to executable code
1584 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001585 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001586 // required to be on a new page boundary
1587 offset = RoundUp(offset, kPageSize);
1588 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001589 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001590 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001591 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001592
Ian Rogers848871b2013-08-05 10:56:33 -07001593 #define DO_TRAMPOLINE(field, fn_name) \
1594 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001595 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1596 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001597 (field) = compiler_driver_->Create ## fn_name(); \
1598 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001599
Ian Rogers848871b2013-08-05 10:56:33 -07001600 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001601 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001602 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001603 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1604 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001605
Ian Rogers848871b2013-08-05 10:56:33 -07001606 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001607 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001608 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1609 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1610 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001611 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001612 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001613 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001614 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001615 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001616 return offset;
1617}
1618
1619size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001620 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1621 return offset;
1622 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001623 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1624 bool success = VisitDexMethods(&code_visitor);
1625 DCHECK(success);
1626 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001627
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001628 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001629 InitImageMethodVisitor image_visitor(this, offset);
1630 success = VisitDexMethods(&image_visitor);
1631 DCHECK(success);
1632 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001633 }
Logan Chien8b977d32012-02-21 19:14:55 +08001634
Brian Carlstrome24fa612011-09-29 00:53:55 -07001635 return offset;
1636}
1637
Vladimir Markoaad75c62016-10-03 08:46:48 +00001638void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001639 if (HasBootImage()) {
1640 DCHECK(bss_string_entries_.empty());
1641 if (bss_type_entries_.empty()) {
1642 // Nothing to put to the .bss section.
1643 return;
1644 }
1645 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001646
1647 // Allocate space for app dex cache arrays in the .bss section.
1648 bss_start_ = RoundUp(oat_size_, kPageSize);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001649 bss_size_ = 0u;
Vladimir Marko1998cd02017-01-13 13:02:58 +00001650 if (!HasBootImage()) {
1651 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1652 for (const DexFile* dex_file : *dex_files_) {
1653 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1654 DexCacheArraysLayout layout(pointer_size, dex_file);
1655 bss_size_ += layout.Size();
1656 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001657 }
1658
1659 bss_roots_offset_ = bss_size_;
1660
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001661 // Prepare offsets for .bss Class entries.
1662 for (auto& entry : bss_type_entries_) {
1663 DCHECK_EQ(entry.second, 0u);
1664 entry.second = bss_start_ + bss_size_;
1665 bss_size_ += sizeof(GcRoot<mirror::Class>);
1666 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001667 // Prepare offsets for .bss String entries.
1668 for (auto& entry : bss_string_entries_) {
1669 DCHECK_EQ(entry.second, 0u);
1670 entry.second = bss_start_ + bss_size_;
1671 bss_size_ += sizeof(GcRoot<mirror::String>);
1672 }
1673}
1674
David Srbeckybc90fd02015-04-22 19:40:27 +01001675bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001676 CHECK(write_state_ == WriteState::kWriteRoData);
1677
Vladimir Markoe079e212016-05-25 12:49:49 +01001678 // Wrap out to update checksum with each write.
1679 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1680 out = &checksum_updating_out;
1681
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001682 if (!WriteClassOffsets(out)) {
1683 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001684 return false;
1685 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001686
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001687 if (!WriteClasses(out)) {
1688 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001689 return false;
1690 }
1691
Vladimir Markof4da6752014-08-01 19:04:18 +01001692 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001693 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001694 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001695 return false;
1696 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001697 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001698 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001699 relative_offset = WriteMaps(out, file_offset, relative_offset);
1700 if (relative_offset == 0) {
1701 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1702 return false;
1703 }
1704
David Srbeckybc90fd02015-04-22 19:40:27 +01001705 // Write padding.
1706 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1707 relative_offset += size_executable_offset_alignment_;
1708 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1709 size_t expected_file_offset = file_offset + relative_offset;
1710 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1711 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1712 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1713 return 0;
1714 }
1715 DCHECK_OFFSET();
1716
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001717 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001718 return true;
1719}
1720
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001721class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1722 public:
1723 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1724 : DexMethodVisitor(writer, offset),
1725 out_(out),
1726 written_bytes_(0u) {}
1727
1728 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1729 const ClassDataItemIterator& it) {
1730 if (it.GetMethodCodeItem() == nullptr) {
1731 // No CodeItem. Native or abstract method.
1732 return true;
1733 }
1734
1735 uint32_t method_idx = it.GetMemberIndex();
1736 CompiledMethod* compiled_method =
1737 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1738
1739 uint32_t length = 0;
1740 const uint8_t* data = nullptr;
1741 // VMap only contains quickening info if this method is not compiled.
1742 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1743 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1744 data = map.data();
1745 length = map.size() * sizeof(map.front());
1746 }
1747
1748 if (!out_->WriteFully(&length, sizeof(length)) ||
1749 !out_->WriteFully(data, length)) {
1750 PLOG(ERROR) << "Failed to write quickening info for "
1751 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1752 return false;
1753 }
1754 offset_ += sizeof(length) + length;
1755 written_bytes_ += sizeof(length) + length;
1756 return true;
1757 }
1758
1759 size_t GetNumberOfWrittenBytes() const {
1760 return written_bytes_;
1761 }
1762
1763 private:
1764 OutputStream* const out_;
1765 size_t written_bytes_;
1766};
1767
1768bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1769 if (!kIsVdexEnabled) {
1770 return true;
1771 }
1772
1773 size_t initial_offset = vdex_size_;
1774 size_t start_offset = RoundUp(initial_offset, 4u);
1775
1776 vdex_size_ = start_offset;
1777 vdex_quickening_info_offset_ = vdex_size_;
1778 size_quickening_info_alignment_ = start_offset - initial_offset;
1779
1780 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1781 if (actual_offset != static_cast<off_t>(start_offset)) {
1782 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1783 << " Expected: " << start_offset
1784 << " Output: " << vdex_out->GetLocation();
1785 return false;
1786 }
1787
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001788 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1789 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1790 if (!VisitDexMethods(&visitor)) {
1791 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1792 return false;
1793 }
1794
1795 if (!vdex_out->Flush()) {
1796 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1797 << " File: " << vdex_out->GetLocation();
1798 return false;
1799 }
1800 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1801 } else {
1802 // We know we did not quicken.
1803 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001804 }
1805
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001806 vdex_size_ += size_quickening_info_;
1807 return true;
1808}
1809
David Brazdil5d5a36b2016-09-14 15:34:10 +01001810bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1811 if (!kIsVdexEnabled) {
1812 return true;
1813 }
1814
1815 if (verifier_deps == nullptr) {
1816 // Nothing to write. Record the offset, but no need
1817 // for alignment.
1818 vdex_verifier_deps_offset_ = vdex_size_;
1819 return true;
1820 }
1821
1822 size_t initial_offset = vdex_size_;
1823 size_t start_offset = RoundUp(initial_offset, 4u);
1824
1825 vdex_size_ = start_offset;
1826 vdex_verifier_deps_offset_ = vdex_size_;
1827 size_verifier_deps_alignment_ = start_offset - initial_offset;
1828
1829 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1830 if (actual_offset != static_cast<off_t>(start_offset)) {
1831 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1832 << " Expected: " << start_offset
1833 << " Output: " << vdex_out->GetLocation();
1834 return false;
1835 }
1836
1837 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001838 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001839
1840 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1841 PLOG(ERROR) << "Failed to write verifier deps."
1842 << " File: " << vdex_out->GetLocation();
1843 return false;
1844 }
1845 if (!vdex_out->Flush()) {
1846 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1847 << " File: " << vdex_out->GetLocation();
1848 return false;
1849 }
1850
1851 size_verifier_deps_ = buffer.size();
1852 vdex_size_ += size_verifier_deps_;
1853 return true;
1854}
1855
David Srbeckybc90fd02015-04-22 19:40:27 +01001856bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001857 CHECK(write_state_ == WriteState::kWriteText);
1858
Vladimir Markoe079e212016-05-25 12:49:49 +01001859 // Wrap out to update checksum with each write.
1860 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1861 out = &checksum_updating_out;
1862
Vladimir Marko944da602016-02-19 12:27:55 +00001863 SetMultiOatRelativePatcherAdjustment();
1864
David Srbeckybc90fd02015-04-22 19:40:27 +01001865 const size_t file_offset = oat_data_offset_;
1866 size_t relative_offset = oat_header_->GetExecutableOffset();
1867 DCHECK_OFFSET();
1868
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001869 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001870 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001871 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001872 return false;
1873 }
1874
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001875 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1876 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001877 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001878 return false;
1879 }
1880
Vladimir Markof4da6752014-08-01 19:04:18 +01001881 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001882 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001883 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1884 return false;
1885 }
1886
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001887 if (kIsDebugBuild) {
1888 uint32_t size_total = 0;
1889 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001890 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1891 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001892
David Brazdil7b49e6c2016-09-01 11:06:18 +01001893 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001894 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001895 DO_STAT(size_dex_file_alignment_);
1896 DO_STAT(size_executable_offset_alignment_);
1897 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001898 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001899 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001900 DO_STAT(size_verifier_deps_);
1901 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001902 DO_STAT(size_quickening_info_);
1903 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001904 DO_STAT(size_interpreter_to_interpreter_bridge_);
1905 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1906 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001907 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001908 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001909 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001910 DO_STAT(size_quick_to_interpreter_bridge_);
1911 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001912 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001913 DO_STAT(size_code_);
1914 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001915 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001916 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001917 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001918 DO_STAT(size_oat_dex_file_location_size_);
1919 DO_STAT(size_oat_dex_file_location_data_);
1920 DO_STAT(size_oat_dex_file_location_checksum_);
1921 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001922 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001923 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001924 DO_STAT(size_oat_lookup_table_alignment_);
1925 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001926 DO_STAT(size_oat_class_offsets_alignment_);
1927 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001928 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001929 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001930 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001931 DO_STAT(size_oat_class_method_offsets_);
1932 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001933
David Brazdil7b49e6c2016-09-01 11:06:18 +01001934 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1935
1936 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1937 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001938 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001939
David Brazdil7b49e6c2016-09-01 11:06:18 +01001940 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1941 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001942
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001943 write_state_ = WriteState::kWriteHeader;
1944 return true;
1945}
1946
1947bool OatWriter::WriteHeader(OutputStream* out,
1948 uint32_t image_file_location_oat_checksum,
1949 uintptr_t image_file_location_oat_begin,
1950 int32_t image_patch_delta) {
1951 CHECK(write_state_ == WriteState::kWriteHeader);
1952
1953 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1954 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001955 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001956 CHECK_EQ(image_patch_delta, 0);
1957 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1958 } else {
1959 CHECK_ALIGNED(image_patch_delta, kPageSize);
1960 oat_header_->SetImagePatchDelta(image_patch_delta);
1961 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001962 oat_header_->UpdateChecksumWithHeaderData();
1963
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001964 const size_t file_offset = oat_data_offset_;
1965
1966 off_t current_offset = out->Seek(0, kSeekCurrent);
1967 if (current_offset == static_cast<off_t>(-1)) {
1968 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1969 return false;
1970 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001971 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001972 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1973 return false;
1974 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001975 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001976
1977 // Flush all other data before writing the header.
1978 if (!out->Flush()) {
1979 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1980 return false;
1981 }
1982 // Write the header.
1983 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001984 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001985 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1986 return false;
1987 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001988 // Flush the header data.
1989 if (!out->Flush()) {
1990 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001991 return false;
1992 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001993
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001994 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1995 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1996 return false;
1997 }
1998 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1999
2000 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002001 return true;
2002}
2003
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002004bool OatWriter::WriteClassOffsets(OutputStream* out) {
2005 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2006 if (oat_dex_file.class_offsets_offset_ != 0u) {
2007 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
2008 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
2009 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2010 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
2011 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00002012 return false;
2013 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002014 if (!oat_dex_file.WriteClassOffsets(this, out)) {
2015 return false;
2016 }
2017 }
2018 }
2019 return true;
2020}
2021
2022bool OatWriter::WriteClasses(OutputStream* out) {
2023 for (OatClass& oat_class : oat_classes_) {
2024 if (!oat_class.Write(this, out, oat_data_offset_)) {
2025 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
2026 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00002027 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002028 }
2029 return true;
2030}
2031
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002032size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002033 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002034 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2035 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2036 return 0;
2037 }
2038 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002039 size_vmap_table_ = relative_offset - vmap_tables_offset;
2040
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002041 return relative_offset;
2042}
2043
2044size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002045 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002046 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002047
Ian Rogers848871b2013-08-05 10:56:33 -07002048 #define DO_TRAMPOLINE(field) \
2049 do { \
2050 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2051 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002052 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002053 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002054 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002055 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002056 return false; \
2057 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002058 size_ ## field += (field)->size(); \
2059 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002060 DCHECK_OFFSET(); \
2061 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002062
Ian Rogers848871b2013-08-05 10:56:33 -07002063 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002064 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002065 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002066 DO_TRAMPOLINE(quick_resolution_trampoline_);
2067 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2068 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002069 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002070 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002071}
2072
Ian Rogers3d504072014-03-01 09:16:49 -08002073size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002074 const size_t file_offset,
2075 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002076 #define VISIT(VisitorType) \
2077 do { \
2078 VisitorType visitor(this, out, file_offset, relative_offset); \
2079 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2080 return 0; \
2081 } \
2082 relative_offset = visitor.GetOffset(); \
2083 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002084
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002085 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002086
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002087 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002088
Vladimir Markob163bb72015-03-31 21:49:49 +01002089 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2090 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2091 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2092
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002093 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002094}
2095
Vladimir Marko944da602016-02-19 12:27:55 +00002096bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002097 // Get the elf file offset of the oat file.
2098 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2099 if (raw_file_offset == static_cast<off_t>(-1)) {
2100 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2101 return false;
2102 }
2103 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2104 return true;
2105}
2106
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002107bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2108 // Read the dex file header and perform minimal verification.
2109 uint8_t raw_header[sizeof(DexFile::Header)];
2110 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2111 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2112 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2113 return false;
2114 }
2115 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2116 return false;
2117 }
2118
2119 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2120 oat_dex_file->dex_file_size_ = header->file_size_;
2121 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2122 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2123 return true;
2124}
2125
2126bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2127 if (!DexFile::IsMagicValid(raw_header)) {
2128 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2129 return false;
2130 }
2131 if (!DexFile::IsVersionValid(raw_header)) {
2132 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2133 return false;
2134 }
2135 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2136 if (header->file_size_ < sizeof(DexFile::Header)) {
2137 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2138 << " File: " << location;
2139 return false;
2140 }
2141 return true;
2142}
2143
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002144bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002145 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002146
David Brazdil7b49e6c2016-09-01 11:06:18 +01002147 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002148
2149 // Write dex files.
2150 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002151 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002152 return false;
2153 }
2154 }
2155
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002156 CloseSources();
2157 return true;
2158}
2159
2160void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002161 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2162 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2163 }
2164 zipped_dex_files_.clear();
2165 zip_archives_.clear();
2166 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002167}
2168
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002169bool OatWriter::WriteDexFile(OutputStream* out,
2170 File* file,
2171 OatDexFile* oat_dex_file,
2172 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002173 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002174 return false;
2175 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002176 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002177 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002178 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2179 return false;
2180 }
2181 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002182 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002183 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002184 return false;
2185 }
2186 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002187 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002188 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002189 return false;
2190 }
2191 } else {
2192 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002193 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002194 return false;
2195 }
2196 }
2197
2198 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002199 if (kIsVdexEnabled) {
2200 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2201 vdex_size_ += oat_dex_file->dex_file_size_;
2202 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002203 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002204 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2205 oat_size_ += oat_dex_file->dex_file_size_;
2206 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002207 size_dex_file_ += oat_dex_file->dex_file_size_;
2208 return true;
2209}
2210
2211bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2212 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002213 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2214 size_t start_offset = RoundUp(initial_offset, 4);
2215 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2216 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002217
2218 // Seek to the start of the dex file and flush any pending operations in the stream.
2219 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002220 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2221 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002222 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002223 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002224 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2225 return false;
2226 }
2227 if (!out->Flush()) {
2228 PLOG(ERROR) << "Failed to flush before writing dex file."
2229 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2230 return false;
2231 }
2232 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002233 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002234 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002235 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002236 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2237 return false;
2238 }
2239
David Brazdil7b49e6c2016-09-01 11:06:18 +01002240 if (kIsVdexEnabled) {
2241 vdex_size_ = start_offset;
2242 } else {
2243 oat_size_ = start_offset;
2244 }
2245 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002246 return true;
2247}
2248
Jeff Hao608f2ce2016-10-19 11:17:11 -07002249bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2250 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2251 std::string error_msg;
2252 std::string location(oat_dex_file->GetLocation());
2253 std::unique_ptr<const DexFile> dex_file;
2254 if (oat_dex_file->source_.IsZipEntry()) {
2255 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2256 std::unique_ptr<MemMap> mem_map(
2257 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2258 dex_file = DexFile::Open(location,
2259 zip_entry->GetCrc32(),
2260 std::move(mem_map),
2261 /* verify */ true,
2262 /* verify_checksum */ true,
2263 &error_msg);
2264 } else {
2265 DCHECK(oat_dex_file->source_.IsRawFile());
2266 File* raw_file = oat_dex_file->source_.GetRawFile();
2267 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2268 }
2269 Options options;
2270 options.output_to_memmap_ = true;
2271 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2272 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2273 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002274 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002275 return false;
2276 }
2277 // Set the checksum of the new oat dex file to be the original file's checksum.
2278 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2279 return true;
2280}
2281
David Brazdil7b49e6c2016-09-01 11:06:18 +01002282bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002283 File* file,
2284 OatDexFile* oat_dex_file,
2285 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002286 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2287 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002288
2289 // Extract the dex file and get the extracted size.
2290 std::string error_msg;
2291 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2292 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2293 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2294 return false;
2295 }
2296 if (file->Flush() != 0) {
2297 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2298 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2299 return false;
2300 }
2301 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2302 if (extracted_end == static_cast<off_t>(-1)) {
2303 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2304 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2305 return false;
2306 }
2307 if (extracted_end < static_cast<off_t>(start_offset)) {
2308 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2309 << " Start: " << start_offset
2310 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2311 return false;
2312 }
2313 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2314 if (extracted_size < sizeof(DexFile::Header)) {
2315 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2316 << extracted_size << " File: " << oat_dex_file->GetLocation();
2317 return false;
2318 }
2319
2320 // Read the dex file header and extract required data to OatDexFile.
2321 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2322 if (actual_offset != static_cast<off_t>(start_offset)) {
2323 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2324 << " Expected: " << start_offset
2325 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2326 return false;
2327 }
2328 if (!ReadDexFileHeader(file, oat_dex_file)) {
2329 return false;
2330 }
2331 if (extracted_size < oat_dex_file->dex_file_size_) {
2332 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2333 << " file size from header: " << oat_dex_file->dex_file_size_
2334 << " File: " << oat_dex_file->GetLocation();
2335 return false;
2336 }
2337
2338 // Override the checksum from header with the CRC from ZIP entry.
2339 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2340
2341 // Seek both file and stream to the end offset.
2342 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2343 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2344 if (actual_offset != static_cast<off_t>(end_offset)) {
2345 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2346 << " Expected: " << end_offset
2347 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2348 return false;
2349 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002350 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002351 if (actual_offset != static_cast<off_t>(end_offset)) {
2352 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2353 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2354 return false;
2355 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002356 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002357 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2358 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2359 return false;
2360 }
2361
2362 // If we extracted more than the size specified in the header, truncate the file.
2363 if (extracted_size > oat_dex_file->dex_file_size_) {
2364 if (file->SetLength(end_offset) != 0) {
2365 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002366 << " File: " << oat_dex_file->GetLocation()
2367 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002368 return false;
2369 }
2370 }
2371
2372 return true;
2373}
2374
David Brazdil7b49e6c2016-09-01 11:06:18 +01002375bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002376 File* file,
2377 OatDexFile* oat_dex_file,
2378 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002379 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2380 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002381
2382 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2383 if (input_offset != static_cast<off_t>(0)) {
2384 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2385 << " Expected: 0"
2386 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2387 return false;
2388 }
2389 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2390 return false;
2391 }
2392
2393 // Copy the input dex file using sendfile().
2394 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2395 PLOG(ERROR) << "Failed to copy dex file to oat file."
2396 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2397 return false;
2398 }
2399 if (file->Flush() != 0) {
2400 PLOG(ERROR) << "Failed to flush dex file."
2401 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2402 return false;
2403 }
2404
2405 // Check file position and seek the stream to the end offset.
2406 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2407 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2408 if (actual_offset != static_cast<off_t>(end_offset)) {
2409 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2410 << " Expected: " << end_offset
2411 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2412 return false;
2413 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002414 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002415 if (actual_offset != static_cast<off_t>(end_offset)) {
2416 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2417 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2418 return false;
2419 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002420 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002421 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2422 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2423 return false;
2424 }
2425
2426 return true;
2427}
2428
David Brazdil7b49e6c2016-09-01 11:06:18 +01002429bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002430 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002431 const uint8_t* dex_file,
2432 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002433 // Note: The raw data has already been checked to contain the header
2434 // and all the data that the header specifies as the file size.
2435 DCHECK(dex_file != nullptr);
2436 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2437 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2438
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002439 if (update_input_vdex) {
2440 // The vdex already contains the dex code, no need to write it again.
2441 } else {
2442 if (!out->WriteFully(dex_file, header->file_size_)) {
2443 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2444 << " to " << out->GetLocation();
2445 return false;
2446 }
2447 if (!out->Flush()) {
2448 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2449 << " File: " << oat_dex_file->GetLocation();
2450 return false;
2451 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002452 }
2453
2454 // Update dex file size and resize class offsets in the OatDexFile.
2455 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002456 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002457 oat_dex_file->dex_file_size_ = header->file_size_;
2458 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2459 return true;
2460}
2461
2462bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2463 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2464
David Brazdil181e1cc2016-09-01 16:38:47 +00002465 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2466 if (initial_offset == static_cast<off_t>(-1)) {
2467 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2468 return false;
2469 }
2470
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002471 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2472 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2473 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2474 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2475 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2476 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2477 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2478 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2479 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2480 return false;
2481 }
2482
2483 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2484 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2485
2486 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2487 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2488
2489 // Write OatDexFile.
2490 if (!oat_dex_file->Write(this, rodata)) {
2491 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2492 return false;
2493 }
2494 }
2495
David Brazdil181e1cc2016-09-01 16:38:47 +00002496 // Seek back to the initial position.
2497 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2498 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2499 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2500 return false;
2501 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002502
David Brazdilb92ba622016-09-01 16:00:30 +00002503 return true;
2504}
2505
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002506bool OatWriter::OpenDexFiles(
2507 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002508 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002509 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2510 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2511 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2512
2513 if (oat_dex_files_.empty()) {
2514 // Nothing to do.
2515 return true;
2516 }
2517
2518 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002519 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2520
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002521 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002522 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2523 length,
2524 PROT_READ | PROT_WRITE,
2525 MAP_SHARED,
2526 file->Fd(),
2527 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2528 /* low_4gb */ false,
2529 file->GetPath().c_str(),
2530 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002531 if (dex_files_map == nullptr) {
2532 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2533 << " error: " << error_msg;
2534 return false;
2535 }
2536 std::vector<std::unique_ptr<const DexFile>> dex_files;
2537 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2538 // Make sure no one messed with input files while we were copying data.
2539 // At the very least we need consistent file size and number of class definitions.
2540 const uint8_t* raw_dex_file =
2541 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2542 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2543 // Note: ValidateDexFileHeader() already logged an error message.
2544 LOG(ERROR) << "Failed to verify written dex file header!"
2545 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2546 << " ~ " << static_cast<const void*>(raw_dex_file);
2547 return false;
2548 }
2549 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2550 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2551 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2552 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2553 << " Output: " << file->GetPath();
2554 return false;
2555 }
2556 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2557 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2558 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2559 << " Output: " << file->GetPath();
2560 return false;
2561 }
2562
2563 // Now, open the dex file.
2564 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2565 oat_dex_file.dex_file_size_,
2566 oat_dex_file.GetLocation(),
2567 oat_dex_file.dex_file_location_checksum_,
2568 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002569 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002570 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002571 &error_msg));
2572 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002573 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2574 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002575 return false;
2576 }
2577 }
2578
2579 *opened_dex_files_map = std::move(dex_files_map);
2580 *opened_dex_files = std::move(dex_files);
2581 return true;
2582}
2583
2584bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002585 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002586 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2587 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2588
David Brazdil7b49e6c2016-09-01 11:06:18 +01002589 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2590 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2591 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2592 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2593 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2594 return false;
2595 }
2596
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002597 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2598 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2599 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002600 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2601
2602 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2603 oat_dex_file->class_offsets_.empty()) {
2604 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002605 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002606
2607 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2608 if (table_size == 0u) {
2609 continue;
2610 }
2611
2612 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002613 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002614 const DexFile& dex_file = *opened_dex_files[i];
2615 {
2616 std::unique_ptr<TypeLookupTable> type_lookup_table =
2617 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2618 type_lookup_table_oat_dex_files_.push_back(
2619 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2620 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2621 }
2622 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002623
2624 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002625 size_t initial_offset = oat_size_;
2626 size_t rodata_offset = RoundUp(initial_offset, 4);
2627 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002628
2629 if (padding_size != 0u) {
2630 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002631 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002632 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2633 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002634 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002635 return false;
2636 }
2637 }
2638
2639 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002640 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002641 DCHECK_EQ(table_size, table->RawDataLength());
2642
David Brazdil7b49e6c2016-09-01 11:06:18 +01002643 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002644 PLOG(ERROR) << "Failed to write lookup table."
2645 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002646 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002647 return false;
2648 }
2649
2650 oat_dex_file->lookup_table_offset_ = rodata_offset;
2651
David Brazdil7b49e6c2016-09-01 11:06:18 +01002652 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002653 size_oat_lookup_table_ += table_size;
2654 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002655 }
2656
David Brazdil7b49e6c2016-09-01 11:06:18 +01002657 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002658 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002659 << " File: " << oat_rodata->GetLocation();
2660 return false;
2661 }
2662
2663 return true;
2664}
2665
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002666bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002667 if (!kIsVdexEnabled) {
2668 return true;
2669 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002670 // Write checksums
2671 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2672 if (actual_offset != sizeof(VdexFile::Header)) {
2673 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2674 << " File: " << vdex_out->GetLocation();
2675 return false;
2676 }
2677
2678 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2679 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2680 if (!vdex_out->WriteFully(
2681 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2682 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2683 << vdex_out->GetLocation();
2684 return false;
2685 }
2686 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2687 }
2688
2689 // Write header.
2690 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002691 if (actual_offset != 0) {
2692 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2693 << " File: " << vdex_out->GetLocation();
2694 return false;
2695 }
2696
David Brazdil5d5a36b2016-09-14 15:34:10 +01002697 DCHECK_NE(vdex_dex_files_offset_, 0u);
2698 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2699
2700 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002701 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2702 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002703
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002704 VdexFile::Header vdex_header(oat_dex_files_.size(),
2705 dex_section_size,
2706 verifier_deps_section_size,
2707 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002708 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2709 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002710 return false;
2711 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002712 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002713
David Brazdil5d5a36b2016-09-14 15:34:10 +01002714 if (!vdex_out->Flush()) {
2715 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2716 << " File: " << vdex_out->GetLocation();
2717 return false;
2718 }
2719
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002720 return true;
2721}
2722
Vladimir Markof4da6752014-08-01 19:04:18 +01002723bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2724 static const uint8_t kPadding[] = {
2725 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2726 };
2727 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002728 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002729 return false;
2730 }
2731 size_code_alignment_ += aligned_code_delta;
2732 return true;
2733}
2734
Vladimir Marko944da602016-02-19 12:27:55 +00002735void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2736 DCHECK(dex_files_ != nullptr);
2737 DCHECK(relative_patcher_ != nullptr);
2738 DCHECK_NE(oat_data_offset_, 0u);
2739 if (image_writer_ != nullptr && !dex_files_->empty()) {
2740 // The oat data begin may not be initialized yet but the oat file offset is ready.
2741 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2742 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2743 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002744 }
2745}
2746
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002747OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2748 DexFileSource source,
2749 CreateTypeLookupTable create_type_lookup_table)
2750 : source_(source),
2751 create_type_lookup_table_(create_type_lookup_table),
2752 dex_file_size_(0),
2753 offset_(0),
2754 dex_file_location_size_(strlen(dex_file_location)),
2755 dex_file_location_data_(dex_file_location),
2756 dex_file_location_checksum_(0u),
2757 dex_file_offset_(0u),
2758 class_offsets_offset_(0u),
2759 lookup_table_offset_(0u),
2760 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002761}
2762
2763size_t OatWriter::OatDexFile::SizeOf() const {
2764 return sizeof(dex_file_location_size_)
2765 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002766 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002767 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002768 + sizeof(class_offsets_offset_)
2769 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002770}
2771
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002772void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2773 DCHECK_EQ(class_offsets_offset_, 0u);
2774 if (!class_offsets_.empty()) {
2775 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002776 size_t initial_offset = oat_writer->oat_size_;
2777 size_t offset = RoundUp(initial_offset, 4);
2778 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002779 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002780 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002781 }
2782}
2783
2784bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2785 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002786 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002787
Vladimir Markoe079e212016-05-25 12:49:49 +01002788 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002789 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002790 return false;
2791 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002792 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002793
Vladimir Markoe079e212016-05-25 12:49:49 +01002794 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002795 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002796 return false;
2797 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002798 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002799
Vladimir Markoe079e212016-05-25 12:49:49 +01002800 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002801 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002802 return false;
2803 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002804 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002805
Vladimir Markoe079e212016-05-25 12:49:49 +01002806 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002807 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002808 return false;
2809 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002810 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002811
Vladimir Markoe079e212016-05-25 12:49:49 +01002812 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002813 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2814 return false;
2815 }
2816 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2817
Vladimir Markoe079e212016-05-25 12:49:49 +01002818 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002819 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2820 return false;
2821 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002822 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002823
2824 return true;
2825}
2826
2827bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002828 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002829 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2830 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002831 return false;
2832 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002833 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002834 return true;
2835}
2836
Brian Carlstromba150c32013-08-27 17:31:03 -07002837OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002838 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002839 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002840 mirror::Class::Status status)
2841 : compiled_methods_(compiled_methods) {
2842 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002843 CHECK_LE(num_non_null_compiled_methods, num_methods);
2844
Brian Carlstrom265091e2013-01-30 14:08:26 -08002845 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002846 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2847
2848 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2849 // apply when there are 0 methods, we just arbitrarily say that 0
2850 // methods means kOatClassNoneCompiled and that we won't use
2851 // kOatClassAllCompiled unless there is at least one compiled
2852 // method. This means in an interpretter only system, we can assert
2853 // that all classes are kOatClassNoneCompiled.
2854 if (num_non_null_compiled_methods == 0) {
2855 type_ = kOatClassNoneCompiled;
2856 } else if (num_non_null_compiled_methods == num_methods) {
2857 type_ = kOatClassAllCompiled;
2858 } else {
2859 type_ = kOatClassSomeCompiled;
2860 }
2861
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002862 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002863 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002864 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002865
2866 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2867 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002868 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002869 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2870 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2871 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2872 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002873 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002874 method_bitmap_size_ = 0;
2875 }
2876
2877 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002878 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002879 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002880 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2881 } else {
2882 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2883 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2884 if (type_ == kOatClassSomeCompiled) {
2885 method_bitmap_->SetBit(i);
2886 }
2887 }
2888 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002889}
2890
Brian Carlstrom265091e2013-01-30 14:08:26 -08002891size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2892 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002893 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2894 if (method_offset == 0) {
2895 return 0;
2896 }
2897 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002898}
2899
2900size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2901 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002902 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002903}
2904
2905size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002906 return sizeof(status_)
2907 + sizeof(type_)
2908 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2909 + method_bitmap_size_
2910 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002911}
2912
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002913bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002914 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002915 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002916 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002917 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002918 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002919 return false;
2920 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002921 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002922
Vladimir Markoe079e212016-05-25 12:49:49 +01002923 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002924 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002925 return false;
2926 }
2927 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002928
Brian Carlstromba150c32013-08-27 17:31:03 -07002929 if (method_bitmap_size_ != 0) {
2930 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002931 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002932 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002933 return false;
2934 }
2935 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002936
Vladimir Markoe079e212016-05-25 12:49:49 +01002937 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002938 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002939 return false;
2940 }
2941 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2942 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002943
Vladimir Markoe079e212016-05-25 12:49:49 +01002944 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002945 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002946 return false;
2947 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002948 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002949 return true;
2950}
2951
Brian Carlstrome24fa612011-09-29 00:53:55 -07002952} // namespace art