blob: fed2d34cdbbbe426f944fb26f60560213df7902b [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"
Vladimir Marko20f85592015-03-19 10:07:02 +000031#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000032#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000033#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "dex_file-inl.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070035#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070036#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010038#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030040#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010041#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010042#include "linker/buffered_output_stream.h"
43#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000044#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000045#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/array.h"
47#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010048#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070049#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010050#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070051#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070052#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070053#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030054#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010055#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010056#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010057#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000058#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070059
60namespace art {
61
Vladimir Marko9bdf1082016-01-21 12:15:52 +000062namespace { // anonymous namespace
63
64typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
65
66const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
67 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
68}
69
Vladimir Markoe079e212016-05-25 12:49:49 +010070class ChecksumUpdatingOutputStream : public OutputStream {
71 public:
72 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
73 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
74
75 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
76 oat_header_->UpdateChecksum(buffer, byte_count);
77 return out_->WriteFully(buffer, byte_count);
78 }
79
80 off_t Seek(off_t offset, Whence whence) OVERRIDE {
81 return out_->Seek(offset, whence);
82 }
83
84 bool Flush() OVERRIDE {
85 return out_->Flush();
86 }
87
88 private:
89 OutputStream* const out_;
90 OatHeader* const oat_header_;
91};
92
Vladimir Marko0c737df2016-08-01 16:33:16 +010093inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
94 // We want to align the code rather than the preheader.
95 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
96 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
97 return aligned_code_offset - unaligned_code_offset;
98}
99
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000100} // anonymous namespace
101
102// Defines the location of the raw dex file to write.
103class OatWriter::DexFileSource {
104 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800105 enum Type {
106 kNone,
107 kZipEntry,
108 kRawFile,
109 kRawData,
110 };
111
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000112 explicit DexFileSource(ZipEntry* zip_entry)
113 : type_(kZipEntry), source_(zip_entry) {
114 DCHECK(source_ != nullptr);
115 }
116
117 explicit DexFileSource(File* raw_file)
118 : type_(kRawFile), source_(raw_file) {
119 DCHECK(source_ != nullptr);
120 }
121
122 explicit DexFileSource(const uint8_t* dex_file)
123 : type_(kRawData), source_(dex_file) {
124 DCHECK(source_ != nullptr);
125 }
126
Mathieu Chartier497d5262017-02-28 20:17:30 -0800127 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000128 bool IsZipEntry() const { return type_ == kZipEntry; }
129 bool IsRawFile() const { return type_ == kRawFile; }
130 bool IsRawData() const { return type_ == kRawData; }
131
132 ZipEntry* GetZipEntry() const {
133 DCHECK(IsZipEntry());
134 DCHECK(source_ != nullptr);
135 return static_cast<ZipEntry*>(const_cast<void*>(source_));
136 }
137
138 File* GetRawFile() const {
139 DCHECK(IsRawFile());
140 DCHECK(source_ != nullptr);
141 return static_cast<File*>(const_cast<void*>(source_));
142 }
143
144 const uint8_t* GetRawData() const {
145 DCHECK(IsRawData());
146 DCHECK(source_ != nullptr);
147 return static_cast<const uint8_t*>(source_);
148 }
149
150 void Clear() {
151 type_ = kNone;
152 source_ = nullptr;
153 }
154
155 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000156 Type type_;
157 const void* source_;
158};
159
Vladimir Marko49b0f452015-12-10 13:49:19 +0000160class OatWriter::OatClass {
161 public:
162 OatClass(size_t offset,
163 const dchecked_vector<CompiledMethod*>& compiled_methods,
164 uint32_t num_non_null_compiled_methods,
165 mirror::Class::Status status);
166 OatClass(OatClass&& src) = default;
167 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
168 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
169 size_t SizeOf() const;
170 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
171
172 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
173 return compiled_methods_[class_def_method_index];
174 }
175
176 // Offset of start of OatClass from beginning of OatHeader. It is
177 // used to validate file position when writing.
178 size_t offset_;
179
180 // CompiledMethods for each class_def_method_index, or null if no method is available.
181 dchecked_vector<CompiledMethod*> compiled_methods_;
182
183 // Offset from OatClass::offset_ to the OatMethodOffsets for the
184 // class_def_method_index. If 0, it means the corresponding
185 // CompiledMethod entry in OatClass::compiled_methods_ should be
186 // null and that the OatClass::type_ should be kOatClassBitmap.
187 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
188
189 // Data to write.
190
191 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
192 int16_t status_;
193
194 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
195 uint16_t type_;
196
197 uint32_t method_bitmap_size_;
198
199 // bit vector indexed by ClassDef method index. When
200 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
201 // method has an OatMethodOffsets in methods_offsets_, otherwise
202 // the entry was ommited to save space. If OatClassType::type_ is
203 // not is kOatClassBitmap, the bitmap will be null.
204 std::unique_ptr<BitVector> method_bitmap_;
205
206 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
207 // present in the OatClass. Note that some may be missing if
208 // OatClass::compiled_methods_ contains null values (and
209 // oat_method_offsets_offsets_from_oat_class_ should contain 0
210 // values in this case).
211 dchecked_vector<OatMethodOffsets> method_offsets_;
212 dchecked_vector<OatQuickMethodHeader> method_headers_;
213
214 private:
215 size_t GetMethodOffsetsRawSize() const {
216 return method_offsets_.size() * sizeof(method_offsets_[0]);
217 }
218
219 DISALLOW_COPY_AND_ASSIGN(OatClass);
220};
221
222class OatWriter::OatDexFile {
223 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000224 OatDexFile(const char* dex_file_location,
225 DexFileSource source,
226 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000227 OatDexFile(OatDexFile&& src) = default;
228
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000229 const char* GetLocation() const {
230 return dex_file_location_data_;
231 }
232
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000233 void ReserveClassOffsets(OatWriter* oat_writer);
234
Vladimir Marko49b0f452015-12-10 13:49:19 +0000235 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000236 bool Write(OatWriter* oat_writer, OutputStream* out) const;
237 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
238
239 // The source of the dex file.
240 DexFileSource source_;
241
242 // Whether to create the type lookup table.
243 CreateTypeLookupTable create_type_lookup_table_;
244
245 // Dex file size. Initialized when writing the dex file.
246 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000247
248 // Offset of start of OatDexFile from beginning of OatHeader. It is
249 // used to validate file position when writing.
250 size_t offset_;
251
252 // Data to write.
253 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000254 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000255 uint32_t dex_file_location_checksum_;
256 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000257 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000258 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000259
260 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000261 dchecked_vector<uint32_t> class_offsets_;
262
263 private:
264 size_t GetClassOffsetsRawSize() const {
265 return class_offsets_.size() * sizeof(class_offsets_[0]);
266 }
267
268 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
269};
270
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100271#define DCHECK_OFFSET() \
272 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
273 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
274
275#define DCHECK_OFFSET_() \
276 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
277 << "file_offset=" << file_offset << " offset_=" << offset_
278
Jeff Hao608f2ce2016-10-19 11:17:11 -0700279OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000280 : write_state_(WriteState::kAddingDexFileSources),
281 timings_(timings),
282 raw_dex_files_(),
283 zip_archives_(),
284 zipped_dex_files_(),
285 zipped_dex_file_locations_(),
286 compiler_driver_(nullptr),
287 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800288 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000289 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100290 vdex_size_(0u),
291 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100292 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100293 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100294 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000295 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000296 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000297 bss_roots_offset_(0u),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000298 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000299 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100300 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700301 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100302 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000303 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700304 size_dex_file_alignment_(0),
305 size_executable_offset_alignment_(0),
306 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700307 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700308 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100309 size_verifier_deps_(0),
310 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100311 size_quickening_info_(0),
312 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700313 size_interpreter_to_interpreter_bridge_(0),
314 size_interpreter_to_compiled_code_bridge_(0),
315 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800316 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700317 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700318 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700319 size_quick_to_interpreter_bridge_(0),
320 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100321 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700322 size_code_(0),
323 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100324 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100325 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700326 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700327 size_method_info_(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_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100714 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700715 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
716 if (!found) {
717 if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
718 // The oat class status is used only for verification of resolved classes,
719 // so use kStatusErrorResolved whether the class was resolved or unresolved
720 // during compile-time verification.
721 status = mirror::Class::kStatusErrorResolved;
722 } else {
723 status = mirror::Class::kStatusNotReady;
724 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100725 }
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();
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700811 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800812 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
813 // to 0-offset and we need to adjust it by code_offset.
814 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100815 if (!compiled_method->GetQuickCode().empty()) {
816 // If the code is compiled, we write the offset of the stack map relative
817 // to the code,
818 if (vmap_table_offset != 0u) {
819 vmap_table_offset += code_offset;
820 DCHECK_LT(vmap_table_offset, code_offset);
821 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700822 if (method_info_offset != 0u) {
823 method_info_offset += code_offset;
824 DCHECK_LT(method_info_offset, code_offset);
825 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100826 } else {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700827 CHECK(compiled_method->GetMethodInfo().empty());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100828 if (kIsVdexEnabled) {
829 // We write the offset in the .vdex file.
830 DCHECK_EQ(vmap_table_offset, 0u);
831 vmap_table_offset = current_quickening_info_offset_;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700832 ArrayRef<const uint8_t> vmap_table = compiled_method->GetVmapTable();
833 current_quickening_info_offset_ += vmap_table.size() * sizeof(vmap_table.front());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100834 } else {
835 // We write the offset of the quickening info relative to the code.
836 vmap_table_offset += code_offset;
837 DCHECK_LT(vmap_table_offset, code_offset);
838 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800839 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800840 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
841 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
842 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100843 *method_header = OatQuickMethodHeader(vmap_table_offset,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700844 method_info_offset,
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100845 frame_size_in_bytes,
846 core_spill_mask,
847 fp_spill_mask,
848 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100849
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000850 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800851 // Update offsets. (Checksum is updated when writing.)
852 offset_ += sizeof(*method_header); // Method header is prepended before code.
853 offset_ += code_size;
854 // Record absolute patch locations.
855 if (!compiled_method->GetPatches().empty()) {
856 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
857 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000858 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100859 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100860 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000861 if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
862 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
863 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
864 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000865 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
866 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
867 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
868 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100869 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100870 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800871 }
Alex Light78382fa2014-06-06 15:45:32 -0700872
David Srbecky91cc06c2016-03-07 16:13:58 +0000873 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000874 // Exclude quickened dex methods (code_size == 0) since they have no native code.
875 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
876 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800877 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000878 debug::MethodDebugInfo info = debug::MethodDebugInfo();
879 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000880 info.dex_file = dex_file_;
881 info.class_def_index = class_def_index_;
882 info.dex_method_index = it.GetMemberIndex();
883 info.access_flags = it.GetMethodAccessFlags();
884 info.code_item = it.GetMethodCodeItem();
885 info.isa = compiled_method->GetInstructionSet();
886 info.deduped = deduped;
887 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
888 info.is_optimized = method_header->IsOptimized();
889 info.is_code_address_text_relative = true;
890 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
891 info.code_size = code_size;
892 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
893 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
894 info.cfi = compiled_method->GetCFIInfo();
895 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100896 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100897
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100898 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
899 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
900 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100901 ++method_offsets_index_;
902 }
903
904 return true;
905 }
906
907 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000908 struct CodeOffsetsKeyComparator {
909 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100910 // Code is deduplicated by CompilerDriver, compare only data pointers.
911 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
912 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000913 }
914 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100915 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
916 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000917 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700918 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
919 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
920 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100921 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
922 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000923 }
924 return false;
925 }
926 };
927
David Srbecky009e2a62015-04-15 02:46:30 +0100928 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
929 const ClassDataItemIterator& it,
930 uint32_t thumb_offset) {
931 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100932 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100933 offset_ += CodeAlignmentSize(offset_, *compiled_method);
934 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100935 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
936 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
937 }
938
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939 // Deduplication is already done on a pointer basis by the compiler driver,
940 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100941 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100942
David Srbecky009e2a62015-04-15 02:46:30 +0100943 // Cache of compiler's --debuggable option.
944 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100945
946 // Offset in the vdex file for the quickening info.
947 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100948};
949
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100950class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
951 public:
952 InitMapMethodVisitor(OatWriter* writer, size_t offset)
953 : OatDexMethodVisitor(writer, offset) {
954 }
955
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700956 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700957 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000958 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
960
961 if (compiled_method != nullptr) {
962 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100963 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
964 // be in the vdex file.
965 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700966 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100967
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100968 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
969 uint32_t map_size = map.size() * sizeof(map[0]);
970 if (map_size != 0u) {
971 size_t offset = dedupe_map_.GetOrCreate(
972 map.data(),
973 [this, map_size]() {
974 uint32_t new_offset = offset_;
975 offset_ += map_size;
976 return new_offset;
977 });
978 // Code offset is not initialized yet, so set the map offset to 0u-offset.
979 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700980 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100981 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100982 }
983 ++method_offsets_index_;
984 }
985
986 return true;
987 }
988
989 private:
990 // Deduplication is already done on a pointer basis by the compiler driver,
991 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100992 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100993};
994
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700995class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
996 public:
997 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
998
999 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
1000 REQUIRES_SHARED(Locks::mutator_lock_) {
1001 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1002 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1003
1004 if (compiled_method != nullptr) {
1005 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1006 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1007 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1008 const uint32_t map_size = map.size() * sizeof(map[0]);
1009 if (map_size != 0u) {
1010 size_t offset = dedupe_map_.GetOrCreate(
1011 map.data(),
1012 [this, map_size]() {
1013 uint32_t new_offset = offset_;
1014 offset_ += map_size;
1015 return new_offset;
1016 });
1017 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1018 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1019 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1020 }
1021 ++method_offsets_index_;
1022 }
1023
1024 return true;
1025 }
1026
1027 private:
1028 // Deduplication is already done on a pointer basis by the compiler driver,
1029 // so we can simply compare the pointers to find out if things are duplicated.
1030 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1031};
1032
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001033class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1034 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001035 InitImageMethodVisitor(OatWriter* writer,
1036 size_t offset,
1037 const std::vector<const DexFile*>* dex_files)
Jeff Haoc7d11882015-02-03 15:08:39 -08001038 : OatDexMethodVisitor(writer, offset),
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001039 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1040 dex_files_(dex_files),
1041 class_linker_(Runtime::Current()->GetClassLinker()) {
1042 }
1043
1044 // Handle copied methods here. Copy pointer to quick code from
1045 // an origin method to a copied method only if they are
1046 // in the same oat file. If the origin and the copied methods are
1047 // in different oat files don't touch the copied method.
1048 // References to other oat files are not supported yet.
1049 bool StartClass(const DexFile* dex_file, size_t class_def_index)
1050 REQUIRES_SHARED(Locks::mutator_lock_) {
1051 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1052 // Skip classes that are not in the image.
1053 if (!IsImageClass()) {
1054 return true;
1055 }
1056 ScopedObjectAccessUnchecked soa(Thread::Current());
1057 StackHandleScope<1> hs(soa.Self());
1058 Handle<mirror::DexCache> dex_cache = hs.NewHandle(
1059 class_linker_->FindDexCache(Thread::Current(), *dex_file));
1060 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1061 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1062 if (klass != nullptr) {
1063 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1064 // Find origin method. Declaring class and dex_method_idx
1065 // in the copied method should be the same as in the origin
1066 // method.
1067 mirror::Class* declaring_class = method.GetDeclaringClass();
1068 ArtMethod* origin = declaring_class->FindDeclaredVirtualMethod(
1069 declaring_class->GetDexCache(),
1070 method.GetDexMethodIndex(),
1071 pointer_size_);
1072 CHECK(origin != nullptr);
1073 if (IsInOatFile(&declaring_class->GetDexFile())) {
1074 const void* code_ptr =
1075 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1076 if (code_ptr == nullptr) {
1077 methods_to_process_.push_back(std::make_pair(&method, origin));
1078 } else {
1079 method.SetEntryPointFromQuickCompiledCodePtrSize(
1080 code_ptr, pointer_size_);
1081 }
1082 }
1083 }
1084 }
1085 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001086 }
1087
1088 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001089 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001090 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001091 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001092 return true;
1093 }
1094
Vladimir Marko49b0f452015-12-10 13:49:19 +00001095 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001096 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1097
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001098 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001099 if (compiled_method != nullptr) {
1100 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1101 offsets = oat_class->method_offsets_[method_offsets_index_];
1102 ++method_offsets_index_;
1103 }
1104
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001105 // Unchecked as we hold mutator_lock_ on entry.
1106 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001107 StackHandleScope<1> hs(soa.Self());
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001108 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker_->FindDexCache(
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001109 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110 ArtMethod* method;
1111 if (writer_->HasBootImage()) {
1112 const InvokeType invoke_type = it.GetMethodInvokeType(
1113 dex_file_->GetClassDef(class_def_index_));
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001114 method = class_linker_->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001115 *dex_file_,
1116 it.GetMemberIndex(),
1117 dex_cache,
1118 ScopedNullHandle<mirror::ClassLoader>(),
1119 nullptr,
1120 invoke_type);
1121 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001122 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001123 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001124 soa.Self()->AssertPendingException();
1125 mirror::Throwable* exc = soa.Self()->GetException();
1126 std::string dump = exc->Dump();
1127 LOG(FATAL) << dump;
1128 UNREACHABLE();
1129 }
1130 } else {
1131 // Should already have been resolved by the compiler, just peek into the dex cache.
1132 // It may not be resolved if the class failed to verify, in this case, don't set the
1133 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001134 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(),
1135 class_linker_->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001136 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001137 if (method != nullptr &&
1138 compiled_method != nullptr &&
1139 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001140 method->SetEntryPointFromQuickCompiledCodePtrSize(
1141 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1142 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001143
1144 return true;
1145 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001146
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001147 // Check whether current class is image class
1148 bool IsImageClass() {
1149 const DexFile::TypeId& type_id =
1150 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1151 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1152 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1153 }
1154
1155 // Check whether specified dex file is in the compiled oat file.
1156 bool IsInOatFile(const DexFile* dex_file) {
1157 return ContainsElement(*dex_files_, dex_file);
1158 }
1159
1160 // Assign a pointer to quick code for copied methods
1161 // not handled in the method StartClass
1162 void Postprocess() {
1163 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1164 ArtMethod* method = p.first;
1165 ArtMethod* origin = p.second;
1166 const void* code_ptr =
1167 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1168 if (code_ptr != nullptr) {
1169 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1170 }
1171 }
1172 }
1173
Jeff Haoc7d11882015-02-03 15:08:39 -08001174 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001175 const PointerSize pointer_size_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001176 const std::vector<const DexFile*>* dex_files_;
1177 ClassLinker* const class_linker_;
1178 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001179};
1180
1181class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1182 public:
1183 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001184 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001185 : OatDexMethodVisitor(writer, relative_offset),
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001186 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001187 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001188 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001189 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001190 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001191 class_linker_(Runtime::Current()->GetClassLinker()),
1192 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001193 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001194 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001195 // If we're creating the image, the address space must be ready so that we can apply patches.
1196 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001197 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001198 }
1199
Vladimir Markof4da6752014-08-01 19:04:18 +01001200 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001201 }
1202
1203 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001204 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001205 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1206 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001207 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001208 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001209 }
1210 return true;
1211 }
1212
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001213 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001214 bool result = OatDexMethodVisitor::EndClass();
1215 if (oat_class_index_ == writer_->oat_classes_.size()) {
1216 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001217 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001218 if (UNLIKELY(offset_ == 0u)) {
1219 PLOG(ERROR) << "Failed to write final relative call thunks";
1220 result = false;
1221 }
1222 }
1223 return result;
1224 }
1225
1226 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001227 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001228 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001229 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1230
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001231 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001232 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001233 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001234 size_t file_offset = file_offset_;
1235 OutputStream* out = out_;
1236
Vladimir Marko35831e82015-09-11 11:59:18 +01001237 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1238 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001239
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001240 // Deduplicate code arrays.
1241 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1242 if (method_offsets.code_offset_ > offset_) {
1243 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1244 if (offset_ == 0u) {
1245 ReportWriteFailure("relative call thunk", it);
1246 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001247 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001248 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1249 if (alignment_size != 0) {
1250 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001251 ReportWriteFailure("code alignment padding", it);
1252 return false;
1253 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001254 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001255 DCHECK_OFFSET_();
1256 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001257 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001258 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1259 DCHECK_EQ(method_offsets.code_offset_,
1260 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001261 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001262 const OatQuickMethodHeader& method_header =
1263 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001264 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001265 ReportWriteFailure("method header", it);
1266 return false;
1267 }
1268 writer_->size_method_header_ += sizeof(method_header);
1269 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001270 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001271
1272 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001273 patched_code_.assign(quick_code.begin(), quick_code.end());
1274 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001275 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001276 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001277 switch (patch.GetType()) {
1278 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001279 // NOTE: Relative calls across oat files are not supported.
1280 uint32_t target_offset = GetTargetOffset(patch);
1281 writer_->relative_patcher_->PatchCall(&patched_code_,
1282 literal_offset,
1283 offset_ + literal_offset,
1284 target_offset);
1285 break;
1286 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001287 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001288 uint32_t target_offset = GetDexCacheOffset(patch);
1289 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1290 patch,
1291 offset_ + literal_offset,
1292 target_offset);
1293 break;
1294 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001295 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001296 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1297 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1298 patch,
1299 offset_ + literal_offset,
1300 target_offset);
1301 break;
1302 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001303 case LinkerPatch::Type::kStringBssEntry: {
1304 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1305 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1306 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1307 patch,
1308 offset_ + literal_offset,
1309 target_offset);
1310 break;
1311 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001312 case LinkerPatch::Type::kTypeRelative: {
1313 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1314 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1315 patch,
1316 offset_ + literal_offset,
1317 target_offset);
1318 break;
1319 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001320 case LinkerPatch::Type::kTypeBssEntry: {
1321 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1322 uint32_t target_offset = writer_->bss_type_entries_.Get(ref);
1323 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1324 patch,
1325 offset_ + literal_offset,
1326 target_offset);
1327 break;
1328 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001329 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001330 uint32_t target_offset = GetTargetOffset(patch);
1331 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1332 break;
1333 }
Vladimir Marko65979462017-05-19 17:25:12 +01001334 case LinkerPatch::Type::kMethodRelative: {
1335 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1336 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1337 patch,
1338 offset_ + literal_offset,
1339 target_offset);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001340 break;
1341 }
Vladimir Markof4f2daa2017-03-20 18:26:59 +00001342 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1343 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1344 patch,
1345 offset_ + literal_offset);
1346 break;
1347 }
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001348 default: {
Richard Uhlerc52f3032017-03-02 13:45:45 +00001349 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001350 break;
1351 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001352 }
1353 }
1354 }
1355
Vladimir Markoe079e212016-05-25 12:49:49 +01001356 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001357 ReportWriteFailure("method code", it);
1358 return false;
1359 }
1360 writer_->size_code_ += code_size;
1361 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001362 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001363 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001364 ++method_offsets_index_;
1365 }
1366
1367 return true;
1368 }
1369
1370 private:
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001371 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001372 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001373 const size_t file_offset_;
1374 const ScopedObjectAccess soa_;
1375 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001376 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001377 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001378 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001379
1380 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1381 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001382 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001383 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001384
Mathieu Chartiere401d142015-04-22 13:56:20 -07001385 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001386 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001387 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001388 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001389 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1390 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001391 ArtMethod* method = dex_cache->GetResolvedMethod(
1392 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001393 CHECK(method != nullptr);
1394 return method;
1395 }
1396
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001397 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001398 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1399 // If there's no new compiled code, either we're compiling an app and the target method
1400 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001401 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001402 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001403 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001404 PointerSize size =
1405 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001406 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1407 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001408 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001409 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1410 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1411 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1412 target_offset = PointerToLowMemUInt32(oat_code_offset);
1413 } else {
1414 target_offset = target->IsNative()
1415 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1416 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1417 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001418 }
1419 return target_offset;
1420 }
1421
Vladimir Markocd556b02017-02-03 11:47:34 +00001422 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001423 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001424 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001425 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001426 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1427 }
1428
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001429 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001430 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001431 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001432 ObjPtr<mirror::Class> type =
1433 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001434 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001435 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001436 }
1437
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001438 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001439 ScopedObjectAccessUnchecked soa(Thread::Current());
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001440 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001441 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1442 patch.TargetStringIndex(),
Vladimir Markof25cc732017-03-16 16:18:15 +00001443 GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001444 DCHECK(string != nullptr);
1445 DCHECK(writer_->HasBootImage() ||
1446 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1447 return string;
1448 }
1449
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001450 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001451 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001452 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1453 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1454 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1455 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001456 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001457 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001458 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1459 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001460 }
1461 }
1462
Vladimir Marko65979462017-05-19 17:25:12 +01001463 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1464 DCHECK(writer_->HasBootImage());
1465 method = writer_->image_writer_->GetImageMethodAddress(method);
1466 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1467 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1468 // TODO: Clean up offset types. The target offset must be treated as signed.
1469 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1470 }
1471
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001472 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001473 DCHECK(writer_->HasBootImage());
1474 object = writer_->image_writer_->GetImageAddress(object);
1475 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1476 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1477 // TODO: Clean up offset types. The target offset must be treated as signed.
1478 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1479 }
1480
Vladimir Markof4da6752014-08-01 19:04:18 +01001481 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001482 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001483 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001484 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001485 } else {
1486 // NOTE: We're using linker patches for app->boot references when the image can
1487 // be relocated and therefore we need to emit .oat_patches. We're not using this
1488 // for app->app references, so check that the object is in the image space.
1489 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001490 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001491 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001492 uint32_t address = PointerToLowMemUInt32(object);
1493 DCHECK_LE(offset + 4, code->size());
1494 uint8_t* data = &(*code)[offset];
1495 data[0] = address & 0xffu;
1496 data[1] = (address >> 8) & 0xffu;
1497 data[2] = (address >> 16) & 0xffu;
1498 data[3] = (address >> 24) & 0xffu;
1499 }
1500
1501 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001502 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001503 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001504 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001505 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1506 // TODO: Clean up offset types.
1507 // The target_offset must be treated as signed for cross-oat patching.
1508 const void* target = reinterpret_cast<const void*>(
1509 writer_->image_writer_->GetOatDataBegin(oat_index) +
1510 static_cast<int32_t>(target_offset));
1511 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001512 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001513 DCHECK_LE(offset + 4, code->size());
1514 uint8_t* data = &(*code)[offset];
1515 data[0] = address & 0xffu;
1516 data[1] = (address >> 8) & 0xffu;
1517 data[2] = (address >> 16) & 0xffu;
1518 data[3] = (address >> 24) & 0xffu;
1519 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001520};
1521
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001522class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1523 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001524 WriteMapMethodVisitor(OatWriter* writer,
1525 OutputStream* out,
1526 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001527 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001528 : OatDexMethodVisitor(writer, relative_offset),
1529 out_(out),
1530 file_offset_(file_offset) {
1531 }
1532
1533 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001534 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001535 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1536
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001537 if (compiled_method != nullptr) { // i.e. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001538 size_t file_offset = file_offset_;
1539 OutputStream* out = out_;
1540
Mingyao Yang063fc772016-08-02 11:02:54 -07001541 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001542 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001543 ++method_offsets_index_;
1544
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001545 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1546 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1547 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001548 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001549
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001550 // If vdex is enabled, only emit the map for compiled code. The quickening info
1551 // is emitted in the vdex already.
1552 if (map_offset != 0u &&
1553 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001554 // Transform map_offset to actual oat data offset.
1555 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1556 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001557 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001558
1559 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1560 size_t map_size = map.size() * sizeof(map[0]);
1561 if (map_offset == offset_) {
1562 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001563 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001564 ReportWriteFailure(it);
1565 return false;
1566 }
1567 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001568 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001569 }
1570 DCHECK_OFFSET_();
1571 }
1572
1573 return true;
1574 }
1575
1576 private:
1577 OutputStream* const out_;
1578 size_t const file_offset_;
1579
1580 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001581 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001582 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001583 }
1584};
1585
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001586class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
1587 public:
1588 WriteMethodInfoVisitor(OatWriter* writer,
1589 OutputStream* out,
1590 const size_t file_offset,
1591 size_t relative_offset)
1592 : OatDexMethodVisitor(writer, relative_offset),
1593 out_(out),
1594 file_offset_(file_offset) {}
1595
1596 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
1597 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1598 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1599
1600 if (compiled_method != nullptr) { // i.e. not an abstract method
1601 size_t file_offset = file_offset_;
1602 OutputStream* out = out_;
1603 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
1604 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
1605 ++method_offsets_index_;
1606 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
1607 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
1608 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
1609 << dex_file_->PrettyMethod(it.GetMemberIndex());
1610 if (map_offset != 0u) {
1611 // Transform map_offset to actual oat data offset.
1612 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1613 DCHECK_NE(map_offset, 0u);
1614 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
1615
1616 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1617 size_t map_size = map.size() * sizeof(map[0]);
1618 if (map_offset == offset_) {
1619 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
1620 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
1621 ReportWriteFailure(it);
1622 return false;
1623 }
1624 offset_ += map_size;
1625 }
1626 }
1627 DCHECK_OFFSET_();
1628 }
1629
1630 return true;
1631 }
1632
1633 private:
1634 OutputStream* const out_;
1635 size_t const file_offset_;
1636
1637 void ReportWriteFailure(const ClassDataItemIterator& it) {
1638 PLOG(ERROR) << "Failed to write map for "
1639 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1640 }
1641};
1642
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001643// Visit all methods from all classes in all dex files with the specified visitor.
1644bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1645 for (const DexFile* dex_file : *dex_files_) {
1646 const size_t class_def_count = dex_file->NumClassDefs();
1647 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1648 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1649 return false;
1650 }
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001651 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001652 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1653 const uint8_t* class_data = dex_file->GetClassData(class_def);
1654 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1655 ClassDataItemIterator it(*dex_file, class_data);
1656 while (it.HasNextStaticField()) {
1657 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001658 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001659 while (it.HasNextInstanceField()) {
1660 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001661 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001662 size_t class_def_method_index = 0u;
1663 while (it.HasNextDirectMethod()) {
1664 if (!visitor->VisitMethod(class_def_method_index, it)) {
1665 return false;
1666 }
1667 ++class_def_method_index;
1668 it.Next();
1669 }
1670 while (it.HasNextVirtualMethod()) {
1671 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1672 return false;
1673 }
1674 ++class_def_method_index;
1675 it.Next();
1676 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001677 }
1678 }
1679 if (UNLIKELY(!visitor->EndClass())) {
1680 return false;
1681 }
1682 }
1683 }
1684 return true;
1685}
1686
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001687size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1688 const InstructionSetFeatures* instruction_set_features,
1689 uint32_t num_dex_files,
1690 SafeMap<std::string, std::string>* key_value_store) {
1691 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1692 oat_header_.reset(OatHeader::Create(instruction_set,
1693 instruction_set_features,
1694 num_dex_files,
1695 key_value_store));
1696 size_oat_header_ += sizeof(OatHeader);
1697 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001698 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001699}
1700
1701size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001702 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1703 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001704 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001705 oat_dex_file.offset_ = offset;
1706 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001707 }
1708 return offset;
1709}
1710
Brian Carlstrom389efb02012-01-11 12:06:26 -08001711size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001712 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001713 InitOatClassesMethodVisitor visitor(this, offset);
1714 bool success = VisitDexMethods(&visitor);
1715 CHECK(success);
1716 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001717
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001718 // Update oat_dex_files_.
1719 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001720 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1721 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001722 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001723 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001724 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001725 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001726 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001727 CHECK(oat_class_it == oat_classes_.end());
1728
1729 return offset;
1730}
1731
1732size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001733 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001734 return offset;
1735 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001736 {
1737 InitMapMethodVisitor visitor(this, offset);
1738 bool success = VisitDexMethods(&visitor);
1739 DCHECK(success);
1740 offset = visitor.GetOffset();
1741 }
1742 {
1743 InitMethodInfoVisitor visitor(this, offset);
1744 bool success = VisitDexMethods(&visitor);
1745 DCHECK(success);
1746 offset = visitor.GetOffset();
1747 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001748 return offset;
1749}
1750
1751size_t OatWriter::InitOatCode(size_t offset) {
1752 // calculate the offsets within OatHeader to executable code
1753 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001754 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001755 // required to be on a new page boundary
1756 offset = RoundUp(offset, kPageSize);
1757 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001758 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001759 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001760 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001761
Ian Rogers848871b2013-08-05 10:56:33 -07001762 #define DO_TRAMPOLINE(field, fn_name) \
1763 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001764 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1765 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001766 (field) = compiler_driver_->Create ## fn_name(); \
1767 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001768
Ian Rogers848871b2013-08-05 10:56:33 -07001769 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001770 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001771 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001772 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1773 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001774
Ian Rogers848871b2013-08-05 10:56:33 -07001775 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001776 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001777 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1778 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1779 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001780 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001781 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001782 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001783 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001784 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001785 return offset;
1786}
1787
1788size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001789 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001790 return offset;
1791 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001792 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1793 bool success = VisitDexMethods(&code_visitor);
1794 DCHECK(success);
1795 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001796
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001797 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001798 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001799 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001800 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001801 DCHECK(success);
1802 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001803 }
Logan Chien8b977d32012-02-21 19:14:55 +08001804
Brian Carlstrome24fa612011-09-29 00:53:55 -07001805 return offset;
1806}
1807
Vladimir Markoaad75c62016-10-03 08:46:48 +00001808void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001809 if (HasBootImage()) {
1810 DCHECK(bss_string_entries_.empty());
1811 if (bss_type_entries_.empty()) {
1812 // Nothing to put to the .bss section.
1813 return;
1814 }
1815 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001816
1817 // Allocate space for app dex cache arrays in the .bss section.
1818 bss_start_ = RoundUp(oat_size_, kPageSize);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001819 bss_size_ = 0u;
Vladimir Marko1998cd02017-01-13 13:02:58 +00001820 if (!HasBootImage()) {
1821 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1822 for (const DexFile* dex_file : *dex_files_) {
1823 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1824 DexCacheArraysLayout layout(pointer_size, dex_file);
1825 bss_size_ += layout.Size();
1826 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001827 }
1828
1829 bss_roots_offset_ = bss_size_;
1830
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001831 // Prepare offsets for .bss Class entries.
1832 for (auto& entry : bss_type_entries_) {
1833 DCHECK_EQ(entry.second, 0u);
1834 entry.second = bss_start_ + bss_size_;
1835 bss_size_ += sizeof(GcRoot<mirror::Class>);
1836 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001837 // Prepare offsets for .bss String entries.
1838 for (auto& entry : bss_string_entries_) {
1839 DCHECK_EQ(entry.second, 0u);
1840 entry.second = bss_start_ + bss_size_;
1841 bss_size_ += sizeof(GcRoot<mirror::String>);
1842 }
1843}
1844
David Srbeckybc90fd02015-04-22 19:40:27 +01001845bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001846 CHECK(write_state_ == WriteState::kWriteRoData);
1847
Vladimir Markoe079e212016-05-25 12:49:49 +01001848 // Wrap out to update checksum with each write.
1849 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1850 out = &checksum_updating_out;
1851
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001852 if (!WriteClassOffsets(out)) {
1853 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001854 return false;
1855 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001856
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001857 if (!WriteClasses(out)) {
1858 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001859 return false;
1860 }
1861
Vladimir Markof4da6752014-08-01 19:04:18 +01001862 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001863 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001864 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001865 return false;
1866 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001867 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001868 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001869 relative_offset = WriteMaps(out, file_offset, relative_offset);
1870 if (relative_offset == 0) {
1871 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1872 return false;
1873 }
1874
David Srbeckybc90fd02015-04-22 19:40:27 +01001875 // Write padding.
1876 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1877 relative_offset += size_executable_offset_alignment_;
1878 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1879 size_t expected_file_offset = file_offset + relative_offset;
1880 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1881 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1882 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1883 return 0;
1884 }
1885 DCHECK_OFFSET();
1886
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001887 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001888 return true;
1889}
1890
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001891class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1892 public:
1893 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1894 : DexMethodVisitor(writer, offset),
1895 out_(out),
1896 written_bytes_(0u) {}
1897
1898 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1899 const ClassDataItemIterator& it) {
1900 if (it.GetMethodCodeItem() == nullptr) {
1901 // No CodeItem. Native or abstract method.
1902 return true;
1903 }
1904
1905 uint32_t method_idx = it.GetMemberIndex();
1906 CompiledMethod* compiled_method =
1907 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1908
1909 uint32_t length = 0;
1910 const uint8_t* data = nullptr;
1911 // VMap only contains quickening info if this method is not compiled.
1912 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1913 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1914 data = map.data();
1915 length = map.size() * sizeof(map.front());
1916 }
1917
1918 if (!out_->WriteFully(&length, sizeof(length)) ||
1919 !out_->WriteFully(data, length)) {
1920 PLOG(ERROR) << "Failed to write quickening info for "
1921 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1922 return false;
1923 }
1924 offset_ += sizeof(length) + length;
1925 written_bytes_ += sizeof(length) + length;
1926 return true;
1927 }
1928
1929 size_t GetNumberOfWrittenBytes() const {
1930 return written_bytes_;
1931 }
1932
1933 private:
1934 OutputStream* const out_;
1935 size_t written_bytes_;
1936};
1937
1938bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1939 if (!kIsVdexEnabled) {
1940 return true;
1941 }
1942
1943 size_t initial_offset = vdex_size_;
1944 size_t start_offset = RoundUp(initial_offset, 4u);
1945
1946 vdex_size_ = start_offset;
1947 vdex_quickening_info_offset_ = vdex_size_;
1948 size_quickening_info_alignment_ = start_offset - initial_offset;
1949
1950 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1951 if (actual_offset != static_cast<off_t>(start_offset)) {
1952 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1953 << " Expected: " << start_offset
1954 << " Output: " << vdex_out->GetLocation();
1955 return false;
1956 }
1957
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001958 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001959 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1960 if (!VisitDexMethods(&visitor)) {
1961 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1962 return false;
1963 }
1964
1965 if (!vdex_out->Flush()) {
1966 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1967 << " File: " << vdex_out->GetLocation();
1968 return false;
1969 }
1970 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1971 } else {
1972 // We know we did not quicken.
1973 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001974 }
1975
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001976 vdex_size_ += size_quickening_info_;
1977 return true;
1978}
1979
David Brazdil5d5a36b2016-09-14 15:34:10 +01001980bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1981 if (!kIsVdexEnabled) {
1982 return true;
1983 }
1984
1985 if (verifier_deps == nullptr) {
1986 // Nothing to write. Record the offset, but no need
1987 // for alignment.
1988 vdex_verifier_deps_offset_ = vdex_size_;
1989 return true;
1990 }
1991
1992 size_t initial_offset = vdex_size_;
1993 size_t start_offset = RoundUp(initial_offset, 4u);
1994
1995 vdex_size_ = start_offset;
1996 vdex_verifier_deps_offset_ = vdex_size_;
1997 size_verifier_deps_alignment_ = start_offset - initial_offset;
1998
1999 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2000 if (actual_offset != static_cast<off_t>(start_offset)) {
2001 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2002 << " Expected: " << start_offset
2003 << " Output: " << vdex_out->GetLocation();
2004 return false;
2005 }
2006
2007 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002008 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002009
2010 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2011 PLOG(ERROR) << "Failed to write verifier deps."
2012 << " File: " << vdex_out->GetLocation();
2013 return false;
2014 }
2015 if (!vdex_out->Flush()) {
2016 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2017 << " File: " << vdex_out->GetLocation();
2018 return false;
2019 }
2020
2021 size_verifier_deps_ = buffer.size();
2022 vdex_size_ += size_verifier_deps_;
2023 return true;
2024}
2025
David Srbeckybc90fd02015-04-22 19:40:27 +01002026bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002027 CHECK(write_state_ == WriteState::kWriteText);
2028
Vladimir Markoe079e212016-05-25 12:49:49 +01002029 // Wrap out to update checksum with each write.
2030 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2031 out = &checksum_updating_out;
2032
Vladimir Marko944da602016-02-19 12:27:55 +00002033 SetMultiOatRelativePatcherAdjustment();
2034
David Srbeckybc90fd02015-04-22 19:40:27 +01002035 const size_t file_offset = oat_data_offset_;
2036 size_t relative_offset = oat_header_->GetExecutableOffset();
2037 DCHECK_OFFSET();
2038
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002039 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002040 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002041 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002042 return false;
2043 }
2044
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002045 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2046 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002047 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002048 return false;
2049 }
2050
Vladimir Markof4da6752014-08-01 19:04:18 +01002051 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002052 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002053 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2054 return false;
2055 }
2056
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002057 if (kIsDebugBuild) {
2058 uint32_t size_total = 0;
2059 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002060 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2061 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002062
David Brazdil7b49e6c2016-09-01 11:06:18 +01002063 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002064 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002065 DO_STAT(size_dex_file_alignment_);
2066 DO_STAT(size_executable_offset_alignment_);
2067 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002068 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002069 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002070 DO_STAT(size_verifier_deps_);
2071 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002072 DO_STAT(size_quickening_info_);
2073 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002074 DO_STAT(size_interpreter_to_interpreter_bridge_);
2075 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2076 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002077 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002078 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002079 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002080 DO_STAT(size_quick_to_interpreter_bridge_);
2081 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002082 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002083 DO_STAT(size_code_);
2084 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002085 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002086 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002087 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002088 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002089 DO_STAT(size_oat_dex_file_location_size_);
2090 DO_STAT(size_oat_dex_file_location_data_);
2091 DO_STAT(size_oat_dex_file_location_checksum_);
2092 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002093 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002094 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002095 DO_STAT(size_oat_lookup_table_alignment_);
2096 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002097 DO_STAT(size_oat_class_offsets_alignment_);
2098 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002099 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002100 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002101 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002102 DO_STAT(size_oat_class_method_offsets_);
2103 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002104
David Brazdil7b49e6c2016-09-01 11:06:18 +01002105 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2106
2107 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2108 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002109 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002110
David Brazdil7b49e6c2016-09-01 11:06:18 +01002111 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2112 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002113
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002114 write_state_ = WriteState::kWriteHeader;
2115 return true;
2116}
2117
2118bool OatWriter::WriteHeader(OutputStream* out,
2119 uint32_t image_file_location_oat_checksum,
2120 uintptr_t image_file_location_oat_begin,
2121 int32_t image_patch_delta) {
2122 CHECK(write_state_ == WriteState::kWriteHeader);
2123
2124 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2125 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002126 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002127 CHECK_EQ(image_patch_delta, 0);
2128 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2129 } else {
2130 CHECK_ALIGNED(image_patch_delta, kPageSize);
2131 oat_header_->SetImagePatchDelta(image_patch_delta);
2132 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002133 oat_header_->UpdateChecksumWithHeaderData();
2134
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002135 const size_t file_offset = oat_data_offset_;
2136
2137 off_t current_offset = out->Seek(0, kSeekCurrent);
2138 if (current_offset == static_cast<off_t>(-1)) {
2139 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2140 return false;
2141 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002142 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002143 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2144 return false;
2145 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002146 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002147
2148 // Flush all other data before writing the header.
2149 if (!out->Flush()) {
2150 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2151 return false;
2152 }
2153 // Write the header.
2154 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002155 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002156 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2157 return false;
2158 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002159 // Flush the header data.
2160 if (!out->Flush()) {
2161 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002162 return false;
2163 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002164
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002165 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2166 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2167 return false;
2168 }
2169 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2170
2171 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002172 return true;
2173}
2174
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002175bool OatWriter::WriteClassOffsets(OutputStream* out) {
2176 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2177 if (oat_dex_file.class_offsets_offset_ != 0u) {
2178 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
2179 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
2180 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2181 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
2182 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00002183 return false;
2184 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002185 if (!oat_dex_file.WriteClassOffsets(this, out)) {
2186 return false;
2187 }
2188 }
2189 }
2190 return true;
2191}
2192
2193bool OatWriter::WriteClasses(OutputStream* out) {
2194 for (OatClass& oat_class : oat_classes_) {
2195 if (!oat_class.Write(this, out, oat_data_offset_)) {
2196 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
2197 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00002198 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002199 }
2200 return true;
2201}
2202
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002203size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002204 {
2205 size_t vmap_tables_offset = relative_offset;
2206 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2207 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2208 return 0;
2209 }
2210 relative_offset = visitor.GetOffset();
2211 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002212 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002213 {
2214 size_t method_infos_offset = relative_offset;
2215 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
2216 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2217 return 0;
2218 }
2219 relative_offset = visitor.GetOffset();
2220 size_method_info_ = relative_offset - method_infos_offset;
2221 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002222
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002223 return relative_offset;
2224}
2225
2226size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002227 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002228 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002229
Ian Rogers848871b2013-08-05 10:56:33 -07002230 #define DO_TRAMPOLINE(field) \
2231 do { \
2232 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2233 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002234 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002235 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002236 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002237 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002238 return false; \
2239 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002240 size_ ## field += (field)->size(); \
2241 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002242 DCHECK_OFFSET(); \
2243 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002244
Ian Rogers848871b2013-08-05 10:56:33 -07002245 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002246 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002247 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002248 DO_TRAMPOLINE(quick_resolution_trampoline_);
2249 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2250 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002251 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002252 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002253}
2254
Ian Rogers3d504072014-03-01 09:16:49 -08002255size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002256 const size_t file_offset,
2257 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002258 #define VISIT(VisitorType) \
2259 do { \
2260 VisitorType visitor(this, out, file_offset, relative_offset); \
2261 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2262 return 0; \
2263 } \
2264 relative_offset = visitor.GetOffset(); \
2265 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002266
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002267 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002268
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002269 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002270
Vladimir Markob163bb72015-03-31 21:49:49 +01002271 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2272 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2273 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2274
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002275 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002276}
2277
Vladimir Marko944da602016-02-19 12:27:55 +00002278bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002279 // Get the elf file offset of the oat file.
2280 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2281 if (raw_file_offset == static_cast<off_t>(-1)) {
2282 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2283 return false;
2284 }
2285 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2286 return true;
2287}
2288
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002289bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2290 // Read the dex file header and perform minimal verification.
2291 uint8_t raw_header[sizeof(DexFile::Header)];
2292 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2293 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2294 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2295 return false;
2296 }
2297 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2298 return false;
2299 }
2300
2301 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2302 oat_dex_file->dex_file_size_ = header->file_size_;
2303 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2304 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2305 return true;
2306}
2307
2308bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2309 if (!DexFile::IsMagicValid(raw_header)) {
2310 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2311 return false;
2312 }
2313 if (!DexFile::IsVersionValid(raw_header)) {
2314 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2315 return false;
2316 }
2317 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2318 if (header->file_size_ < sizeof(DexFile::Header)) {
2319 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2320 << " File: " << location;
2321 return false;
2322 }
2323 return true;
2324}
2325
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002326bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002327 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002328
David Brazdil7b49e6c2016-09-01 11:06:18 +01002329 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002330
2331 // Write dex files.
2332 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002333 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002334 return false;
2335 }
2336 }
2337
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002338 CloseSources();
2339 return true;
2340}
2341
2342void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002343 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2344 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2345 }
2346 zipped_dex_files_.clear();
2347 zip_archives_.clear();
2348 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002349}
2350
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002351bool OatWriter::WriteDexFile(OutputStream* out,
2352 File* file,
2353 OatDexFile* oat_dex_file,
2354 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002355 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002356 return false;
2357 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002358 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002359 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002360 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2361 return false;
2362 }
2363 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002364 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002365 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002366 return false;
2367 }
2368 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002369 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002370 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002371 return false;
2372 }
2373 } else {
2374 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002375 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002376 return false;
2377 }
2378 }
2379
2380 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002381 if (kIsVdexEnabled) {
2382 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2383 vdex_size_ += oat_dex_file->dex_file_size_;
2384 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002385 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002386 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2387 oat_size_ += oat_dex_file->dex_file_size_;
2388 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002389 size_dex_file_ += oat_dex_file->dex_file_size_;
2390 return true;
2391}
2392
2393bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2394 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002395 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2396 size_t start_offset = RoundUp(initial_offset, 4);
2397 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2398 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002399
2400 // Seek to the start of the dex file and flush any pending operations in the stream.
2401 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002402 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2403 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002404 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002405 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002406 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2407 return false;
2408 }
2409 if (!out->Flush()) {
2410 PLOG(ERROR) << "Failed to flush before writing dex file."
2411 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2412 return false;
2413 }
2414 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002415 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002416 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002417 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002418 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2419 return false;
2420 }
2421
David Brazdil7b49e6c2016-09-01 11:06:18 +01002422 if (kIsVdexEnabled) {
2423 vdex_size_ = start_offset;
2424 } else {
2425 oat_size_ = start_offset;
2426 }
2427 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002428 return true;
2429}
2430
Jeff Hao608f2ce2016-10-19 11:17:11 -07002431bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2432 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2433 std::string error_msg;
2434 std::string location(oat_dex_file->GetLocation());
2435 std::unique_ptr<const DexFile> dex_file;
2436 if (oat_dex_file->source_.IsZipEntry()) {
2437 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2438 std::unique_ptr<MemMap> mem_map(
2439 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08002440 if (mem_map == nullptr) {
2441 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
2442 return false;
2443 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002444 dex_file = DexFile::Open(location,
2445 zip_entry->GetCrc32(),
2446 std::move(mem_map),
2447 /* verify */ true,
2448 /* verify_checksum */ true,
2449 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01002450 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002451 File* raw_file = oat_dex_file->source_.GetRawFile();
2452 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01002453 } else {
2454 // The source data is a vdex file.
2455 CHECK(oat_dex_file->source_.IsRawData())
2456 << static_cast<size_t>(oat_dex_file->source_.GetType());
2457 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
2458 // Note: The raw data has already been checked to contain the header
2459 // and all the data that the header specifies as the file size.
2460 DCHECK(raw_dex_file != nullptr);
2461 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
2462 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2463 // Since the source may have had its layout changed, or may be quickened, don't verify it.
2464 dex_file = DexFile::Open(raw_dex_file,
2465 header->file_size_,
2466 location,
2467 oat_dex_file->dex_file_location_checksum_,
2468 nullptr,
2469 /* verify */ false,
2470 /* verify_checksum */ false,
2471 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002472 }
Jeff Haode197542017-02-03 10:48:13 -08002473 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08002474 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08002475 return false;
2476 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002477 Options options;
2478 options.output_to_memmap_ = true;
2479 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2480 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2481 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002482 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002483 return false;
2484 }
2485 // Set the checksum of the new oat dex file to be the original file's checksum.
2486 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2487 return true;
2488}
2489
David Brazdil7b49e6c2016-09-01 11:06:18 +01002490bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002491 File* file,
2492 OatDexFile* oat_dex_file,
2493 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002494 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2495 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002496
2497 // Extract the dex file and get the extracted size.
2498 std::string error_msg;
2499 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2500 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2501 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2502 return false;
2503 }
2504 if (file->Flush() != 0) {
2505 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2506 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2507 return false;
2508 }
2509 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2510 if (extracted_end == static_cast<off_t>(-1)) {
2511 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2512 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2513 return false;
2514 }
2515 if (extracted_end < static_cast<off_t>(start_offset)) {
2516 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2517 << " Start: " << start_offset
2518 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2519 return false;
2520 }
2521 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2522 if (extracted_size < sizeof(DexFile::Header)) {
2523 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2524 << extracted_size << " File: " << oat_dex_file->GetLocation();
2525 return false;
2526 }
2527
2528 // Read the dex file header and extract required data to OatDexFile.
2529 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2530 if (actual_offset != static_cast<off_t>(start_offset)) {
2531 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2532 << " Expected: " << start_offset
2533 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2534 return false;
2535 }
2536 if (!ReadDexFileHeader(file, oat_dex_file)) {
2537 return false;
2538 }
2539 if (extracted_size < oat_dex_file->dex_file_size_) {
2540 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2541 << " file size from header: " << oat_dex_file->dex_file_size_
2542 << " File: " << oat_dex_file->GetLocation();
2543 return false;
2544 }
2545
2546 // Override the checksum from header with the CRC from ZIP entry.
2547 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2548
2549 // Seek both file and stream to the end offset.
2550 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2551 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2552 if (actual_offset != static_cast<off_t>(end_offset)) {
2553 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2554 << " Expected: " << end_offset
2555 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2556 return false;
2557 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002558 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002559 if (actual_offset != static_cast<off_t>(end_offset)) {
2560 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2561 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2562 return false;
2563 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002564 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002565 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2566 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2567 return false;
2568 }
2569
2570 // If we extracted more than the size specified in the header, truncate the file.
2571 if (extracted_size > oat_dex_file->dex_file_size_) {
2572 if (file->SetLength(end_offset) != 0) {
2573 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002574 << " File: " << oat_dex_file->GetLocation()
2575 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002576 return false;
2577 }
2578 }
2579
2580 return true;
2581}
2582
David Brazdil7b49e6c2016-09-01 11:06:18 +01002583bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002584 File* file,
2585 OatDexFile* oat_dex_file,
2586 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002587 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2588 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002589
2590 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2591 if (input_offset != static_cast<off_t>(0)) {
2592 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2593 << " Expected: 0"
2594 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2595 return false;
2596 }
2597 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2598 return false;
2599 }
2600
2601 // Copy the input dex file using sendfile().
2602 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2603 PLOG(ERROR) << "Failed to copy dex file to oat file."
2604 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2605 return false;
2606 }
2607 if (file->Flush() != 0) {
2608 PLOG(ERROR) << "Failed to flush dex file."
2609 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2610 return false;
2611 }
2612
2613 // Check file position and seek the stream to the end offset.
2614 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2615 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2616 if (actual_offset != static_cast<off_t>(end_offset)) {
2617 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2618 << " Expected: " << end_offset
2619 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2620 return false;
2621 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002622 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002623 if (actual_offset != static_cast<off_t>(end_offset)) {
2624 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2625 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2626 return false;
2627 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002628 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002629 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2630 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2631 return false;
2632 }
2633
2634 return true;
2635}
2636
David Brazdil7b49e6c2016-09-01 11:06:18 +01002637bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002638 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002639 const uint8_t* dex_file,
2640 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002641 // Note: The raw data has already been checked to contain the header
2642 // and all the data that the header specifies as the file size.
2643 DCHECK(dex_file != nullptr);
2644 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2645 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2646
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002647 if (update_input_vdex) {
2648 // The vdex already contains the dex code, no need to write it again.
2649 } else {
2650 if (!out->WriteFully(dex_file, header->file_size_)) {
2651 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2652 << " to " << out->GetLocation();
2653 return false;
2654 }
2655 if (!out->Flush()) {
2656 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2657 << " File: " << oat_dex_file->GetLocation();
2658 return false;
2659 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002660 }
2661
2662 // Update dex file size and resize class offsets in the OatDexFile.
2663 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002664 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002665 oat_dex_file->dex_file_size_ = header->file_size_;
2666 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2667 return true;
2668}
2669
2670bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2671 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2672
David Brazdil181e1cc2016-09-01 16:38:47 +00002673 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2674 if (initial_offset == static_cast<off_t>(-1)) {
2675 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2676 return false;
2677 }
2678
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002679 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2680 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2681 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2682 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2683 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2684 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2685 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2686 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2687 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2688 return false;
2689 }
2690
2691 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2692 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2693
2694 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2695 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2696
2697 // Write OatDexFile.
2698 if (!oat_dex_file->Write(this, rodata)) {
2699 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2700 return false;
2701 }
2702 }
2703
David Brazdil181e1cc2016-09-01 16:38:47 +00002704 // Seek back to the initial position.
2705 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2706 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2707 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2708 return false;
2709 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002710
David Brazdilb92ba622016-09-01 16:00:30 +00002711 return true;
2712}
2713
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002714bool OatWriter::OpenDexFiles(
2715 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002716 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002717 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2718 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2719 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2720
2721 if (oat_dex_files_.empty()) {
2722 // Nothing to do.
2723 return true;
2724 }
2725
2726 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002727 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2728
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002729 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002730 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2731 length,
2732 PROT_READ | PROT_WRITE,
2733 MAP_SHARED,
2734 file->Fd(),
2735 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2736 /* low_4gb */ false,
2737 file->GetPath().c_str(),
2738 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002739 if (dex_files_map == nullptr) {
2740 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2741 << " error: " << error_msg;
2742 return false;
2743 }
2744 std::vector<std::unique_ptr<const DexFile>> dex_files;
2745 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2746 // Make sure no one messed with input files while we were copying data.
2747 // At the very least we need consistent file size and number of class definitions.
2748 const uint8_t* raw_dex_file =
2749 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2750 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2751 // Note: ValidateDexFileHeader() already logged an error message.
2752 LOG(ERROR) << "Failed to verify written dex file header!"
2753 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2754 << " ~ " << static_cast<const void*>(raw_dex_file);
2755 return false;
2756 }
2757 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2758 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2759 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2760 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2761 << " Output: " << file->GetPath();
2762 return false;
2763 }
2764 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2765 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2766 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2767 << " Output: " << file->GetPath();
2768 return false;
2769 }
2770
2771 // Now, open the dex file.
2772 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2773 oat_dex_file.dex_file_size_,
2774 oat_dex_file.GetLocation(),
2775 oat_dex_file.dex_file_location_checksum_,
2776 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002777 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002778 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002779 &error_msg));
2780 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002781 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2782 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002783 return false;
2784 }
2785 }
2786
2787 *opened_dex_files_map = std::move(dex_files_map);
2788 *opened_dex_files = std::move(dex_files);
2789 return true;
2790}
2791
2792bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002793 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002794 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2795 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2796
David Brazdil7b49e6c2016-09-01 11:06:18 +01002797 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2798 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2799 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2800 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2801 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2802 return false;
2803 }
2804
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002805 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2806 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2807 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002808 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2809
2810 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2811 oat_dex_file->class_offsets_.empty()) {
2812 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002813 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002814
2815 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2816 if (table_size == 0u) {
2817 continue;
2818 }
2819
2820 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002821 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002822 const DexFile& dex_file = *opened_dex_files[i];
2823 {
2824 std::unique_ptr<TypeLookupTable> type_lookup_table =
2825 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2826 type_lookup_table_oat_dex_files_.push_back(
2827 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2828 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2829 }
2830 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002831
2832 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002833 size_t initial_offset = oat_size_;
2834 size_t rodata_offset = RoundUp(initial_offset, 4);
2835 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002836
2837 if (padding_size != 0u) {
2838 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002839 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002840 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2841 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002842 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002843 return false;
2844 }
2845 }
2846
2847 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002848 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002849 DCHECK_EQ(table_size, table->RawDataLength());
2850
David Brazdil7b49e6c2016-09-01 11:06:18 +01002851 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002852 PLOG(ERROR) << "Failed to write lookup table."
2853 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002854 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002855 return false;
2856 }
2857
2858 oat_dex_file->lookup_table_offset_ = rodata_offset;
2859
David Brazdil7b49e6c2016-09-01 11:06:18 +01002860 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002861 size_oat_lookup_table_ += table_size;
2862 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002863 }
2864
David Brazdil7b49e6c2016-09-01 11:06:18 +01002865 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002866 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002867 << " File: " << oat_rodata->GetLocation();
2868 return false;
2869 }
2870
2871 return true;
2872}
2873
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002874bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002875 if (!kIsVdexEnabled) {
2876 return true;
2877 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002878 // Write checksums
2879 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2880 if (actual_offset != sizeof(VdexFile::Header)) {
2881 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2882 << " File: " << vdex_out->GetLocation();
2883 return false;
2884 }
2885
2886 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2887 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2888 if (!vdex_out->WriteFully(
2889 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2890 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2891 << vdex_out->GetLocation();
2892 return false;
2893 }
2894 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2895 }
2896
2897 // Write header.
2898 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002899 if (actual_offset != 0) {
2900 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2901 << " File: " << vdex_out->GetLocation();
2902 return false;
2903 }
2904
David Brazdil5d5a36b2016-09-14 15:34:10 +01002905 DCHECK_NE(vdex_dex_files_offset_, 0u);
2906 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2907
2908 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002909 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2910 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002911
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002912 VdexFile::Header vdex_header(oat_dex_files_.size(),
2913 dex_section_size,
2914 verifier_deps_section_size,
2915 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002916 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2917 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002918 return false;
2919 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002920 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002921
David Brazdil5d5a36b2016-09-14 15:34:10 +01002922 if (!vdex_out->Flush()) {
2923 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2924 << " File: " << vdex_out->GetLocation();
2925 return false;
2926 }
2927
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002928 return true;
2929}
2930
Vladimir Markof4da6752014-08-01 19:04:18 +01002931bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2932 static const uint8_t kPadding[] = {
2933 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2934 };
2935 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002936 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002937 return false;
2938 }
2939 size_code_alignment_ += aligned_code_delta;
2940 return true;
2941}
2942
Vladimir Marko944da602016-02-19 12:27:55 +00002943void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2944 DCHECK(dex_files_ != nullptr);
2945 DCHECK(relative_patcher_ != nullptr);
2946 DCHECK_NE(oat_data_offset_, 0u);
2947 if (image_writer_ != nullptr && !dex_files_->empty()) {
2948 // The oat data begin may not be initialized yet but the oat file offset is ready.
2949 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2950 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2951 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002952 }
2953}
2954
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002955OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2956 DexFileSource source,
2957 CreateTypeLookupTable create_type_lookup_table)
2958 : source_(source),
2959 create_type_lookup_table_(create_type_lookup_table),
2960 dex_file_size_(0),
2961 offset_(0),
2962 dex_file_location_size_(strlen(dex_file_location)),
2963 dex_file_location_data_(dex_file_location),
2964 dex_file_location_checksum_(0u),
2965 dex_file_offset_(0u),
2966 class_offsets_offset_(0u),
2967 lookup_table_offset_(0u),
2968 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002969}
2970
2971size_t OatWriter::OatDexFile::SizeOf() const {
2972 return sizeof(dex_file_location_size_)
2973 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002974 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002975 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002976 + sizeof(class_offsets_offset_)
2977 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002978}
2979
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002980void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2981 DCHECK_EQ(class_offsets_offset_, 0u);
2982 if (!class_offsets_.empty()) {
2983 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002984 size_t initial_offset = oat_writer->oat_size_;
2985 size_t offset = RoundUp(initial_offset, 4);
2986 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002987 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002988 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002989 }
2990}
2991
2992bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2993 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002994 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002995
Vladimir Markoe079e212016-05-25 12:49:49 +01002996 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002997 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002998 return false;
2999 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003000 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003001
Vladimir Markoe079e212016-05-25 12:49:49 +01003002 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003003 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003004 return false;
3005 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003006 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003007
Vladimir Markoe079e212016-05-25 12:49:49 +01003008 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003009 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003010 return false;
3011 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003012 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003013
Vladimir Markoe079e212016-05-25 12:49:49 +01003014 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003015 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003016 return false;
3017 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003018 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003019
Vladimir Markoe079e212016-05-25 12:49:49 +01003020 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003021 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3022 return false;
3023 }
3024 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3025
Vladimir Markoe079e212016-05-25 12:49:49 +01003026 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003027 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3028 return false;
3029 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003030 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003031
3032 return true;
3033}
3034
3035bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003036 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003037 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
3038 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003039 return false;
3040 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003041 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003042 return true;
3043}
3044
Brian Carlstromba150c32013-08-27 17:31:03 -07003045OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00003046 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07003047 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003048 mirror::Class::Status status)
3049 : compiled_methods_(compiled_methods) {
3050 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07003051 CHECK_LE(num_non_null_compiled_methods, num_methods);
3052
Brian Carlstrom265091e2013-01-30 14:08:26 -08003053 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07003054 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
3055
3056 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
3057 // apply when there are 0 methods, we just arbitrarily say that 0
3058 // methods means kOatClassNoneCompiled and that we won't use
3059 // kOatClassAllCompiled unless there is at least one compiled
3060 // method. This means in an interpretter only system, we can assert
3061 // that all classes are kOatClassNoneCompiled.
3062 if (num_non_null_compiled_methods == 0) {
3063 type_ = kOatClassNoneCompiled;
3064 } else if (num_non_null_compiled_methods == num_methods) {
3065 type_ = kOatClassAllCompiled;
3066 } else {
3067 type_ = kOatClassSomeCompiled;
3068 }
3069
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003070 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07003071 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01003072 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07003073
3074 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
3075 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003076 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07003077 method_bitmap_size_ = method_bitmap_->GetSizeOf();
3078 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
3079 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
3080 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003081 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07003082 method_bitmap_size_ = 0;
3083 }
3084
3085 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003086 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003087 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003088 oat_method_offsets_offsets_from_oat_class_[i] = 0;
3089 } else {
3090 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
3091 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
3092 if (type_ == kOatClassSomeCompiled) {
3093 method_bitmap_->SetBit(i);
3094 }
3095 }
3096 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003097}
3098
Brian Carlstrom265091e2013-01-30 14:08:26 -08003099size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
3100 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003101 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
3102 if (method_offset == 0) {
3103 return 0;
3104 }
3105 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003106}
3107
3108size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
3109 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003110 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08003111}
3112
3113size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003114 return sizeof(status_)
3115 + sizeof(type_)
3116 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
3117 + method_bitmap_size_
3118 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07003119}
3120
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003121bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08003122 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003123 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08003124 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01003125 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003126 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003127 return false;
3128 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003129 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003130
Vladimir Markoe079e212016-05-25 12:49:49 +01003131 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003132 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003133 return false;
3134 }
3135 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003136
Brian Carlstromba150c32013-08-27 17:31:03 -07003137 if (method_bitmap_size_ != 0) {
3138 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01003139 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003140 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003141 return false;
3142 }
3143 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003144
Vladimir Markoe079e212016-05-25 12:49:49 +01003145 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003146 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003147 return false;
3148 }
3149 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
3150 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003151
Vladimir Markoe079e212016-05-25 12:49:49 +01003152 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08003153 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003154 return false;
3155 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003156 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003157 return true;
3158}
3159
Brian Carlstrome24fa612011-09-29 00:53:55 -07003160} // namespace art