blob: 8e25aa342100160fb8787894b30af41200cbe3be [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000027#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070030#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070031#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000032#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000033#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "dex_file-inl.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070036#include "dexlayout.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "driver/compiler_driver.h"
38#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010039#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010042#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010043#include "linker/buffered_output_stream.h"
44#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000045#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000046#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/array.h"
48#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010049#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010051#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070052#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070053#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030055#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010056#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010057#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070058#include "verifier/method_verifier.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010059#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000060#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070061
62namespace art {
63
Vladimir Marko9bdf1082016-01-21 12:15:52 +000064namespace { // anonymous namespace
65
66typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
67
68const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
69 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
70}
71
Vladimir Markoe079e212016-05-25 12:49:49 +010072class ChecksumUpdatingOutputStream : public OutputStream {
73 public:
74 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
75 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
76
77 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
78 oat_header_->UpdateChecksum(buffer, byte_count);
79 return out_->WriteFully(buffer, byte_count);
80 }
81
82 off_t Seek(off_t offset, Whence whence) OVERRIDE {
83 return out_->Seek(offset, whence);
84 }
85
86 bool Flush() OVERRIDE {
87 return out_->Flush();
88 }
89
90 private:
91 OutputStream* const out_;
92 OatHeader* const oat_header_;
93};
94
Vladimir Marko0c737df2016-08-01 16:33:16 +010095inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
96 // We want to align the code rather than the preheader.
97 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
98 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
99 return aligned_code_offset - unaligned_code_offset;
100}
101
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000102} // anonymous namespace
103
104// Defines the location of the raw dex file to write.
105class OatWriter::DexFileSource {
106 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800107 enum Type {
108 kNone,
109 kZipEntry,
110 kRawFile,
111 kRawData,
112 };
113
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000114 explicit DexFileSource(ZipEntry* zip_entry)
115 : type_(kZipEntry), source_(zip_entry) {
116 DCHECK(source_ != nullptr);
117 }
118
119 explicit DexFileSource(File* raw_file)
120 : type_(kRawFile), source_(raw_file) {
121 DCHECK(source_ != nullptr);
122 }
123
124 explicit DexFileSource(const uint8_t* dex_file)
125 : type_(kRawData), source_(dex_file) {
126 DCHECK(source_ != nullptr);
127 }
128
Mathieu Chartier497d5262017-02-28 20:17:30 -0800129 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000130 bool IsZipEntry() const { return type_ == kZipEntry; }
131 bool IsRawFile() const { return type_ == kRawFile; }
132 bool IsRawData() const { return type_ == kRawData; }
133
134 ZipEntry* GetZipEntry() const {
135 DCHECK(IsZipEntry());
136 DCHECK(source_ != nullptr);
137 return static_cast<ZipEntry*>(const_cast<void*>(source_));
138 }
139
140 File* GetRawFile() const {
141 DCHECK(IsRawFile());
142 DCHECK(source_ != nullptr);
143 return static_cast<File*>(const_cast<void*>(source_));
144 }
145
146 const uint8_t* GetRawData() const {
147 DCHECK(IsRawData());
148 DCHECK(source_ != nullptr);
149 return static_cast<const uint8_t*>(source_);
150 }
151
152 void Clear() {
153 type_ = kNone;
154 source_ = nullptr;
155 }
156
157 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000158 Type type_;
159 const void* source_;
160};
161
Vladimir Marko49b0f452015-12-10 13:49:19 +0000162class OatWriter::OatClass {
163 public:
164 OatClass(size_t offset,
165 const dchecked_vector<CompiledMethod*>& compiled_methods,
166 uint32_t num_non_null_compiled_methods,
167 mirror::Class::Status status);
168 OatClass(OatClass&& src) = default;
169 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
170 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
171 size_t SizeOf() const;
172 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
173
174 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
175 return compiled_methods_[class_def_method_index];
176 }
177
178 // Offset of start of OatClass from beginning of OatHeader. It is
179 // used to validate file position when writing.
180 size_t offset_;
181
182 // CompiledMethods for each class_def_method_index, or null if no method is available.
183 dchecked_vector<CompiledMethod*> compiled_methods_;
184
185 // Offset from OatClass::offset_ to the OatMethodOffsets for the
186 // class_def_method_index. If 0, it means the corresponding
187 // CompiledMethod entry in OatClass::compiled_methods_ should be
188 // null and that the OatClass::type_ should be kOatClassBitmap.
189 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
190
191 // Data to write.
192
193 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
194 int16_t status_;
195
196 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
197 uint16_t type_;
198
199 uint32_t method_bitmap_size_;
200
201 // bit vector indexed by ClassDef method index. When
202 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
203 // method has an OatMethodOffsets in methods_offsets_, otherwise
204 // the entry was ommited to save space. If OatClassType::type_ is
205 // not is kOatClassBitmap, the bitmap will be null.
206 std::unique_ptr<BitVector> method_bitmap_;
207
208 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
209 // present in the OatClass. Note that some may be missing if
210 // OatClass::compiled_methods_ contains null values (and
211 // oat_method_offsets_offsets_from_oat_class_ should contain 0
212 // values in this case).
213 dchecked_vector<OatMethodOffsets> method_offsets_;
214 dchecked_vector<OatQuickMethodHeader> method_headers_;
215
216 private:
217 size_t GetMethodOffsetsRawSize() const {
218 return method_offsets_.size() * sizeof(method_offsets_[0]);
219 }
220
221 DISALLOW_COPY_AND_ASSIGN(OatClass);
222};
223
224class OatWriter::OatDexFile {
225 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000226 OatDexFile(const char* dex_file_location,
227 DexFileSource source,
228 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000229 OatDexFile(OatDexFile&& src) = default;
230
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000231 const char* GetLocation() const {
232 return dex_file_location_data_;
233 }
234
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000235 void ReserveClassOffsets(OatWriter* oat_writer);
236
Vladimir Marko49b0f452015-12-10 13:49:19 +0000237 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000238 bool Write(OatWriter* oat_writer, OutputStream* out) const;
239 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
240
241 // The source of the dex file.
242 DexFileSource source_;
243
244 // Whether to create the type lookup table.
245 CreateTypeLookupTable create_type_lookup_table_;
246
247 // Dex file size. Initialized when writing the dex file.
248 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000249
250 // Offset of start of OatDexFile from beginning of OatHeader. It is
251 // used to validate file position when writing.
252 size_t offset_;
253
254 // Data to write.
255 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000256 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000257 uint32_t dex_file_location_checksum_;
258 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000259 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000260 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000261
262 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000263 dchecked_vector<uint32_t> class_offsets_;
264
265 private:
266 size_t GetClassOffsetsRawSize() const {
267 return class_offsets_.size() * sizeof(class_offsets_[0]);
268 }
269
270 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
271};
272
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100273#define DCHECK_OFFSET() \
274 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
275 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
276
277#define DCHECK_OFFSET_() \
278 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
279 << "file_offset=" << file_offset << " offset_=" << offset_
280
Jeff Hao608f2ce2016-10-19 11:17:11 -0700281OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000282 : write_state_(WriteState::kAddingDexFileSources),
283 timings_(timings),
284 raw_dex_files_(),
285 zip_archives_(),
286 zipped_dex_files_(),
287 zipped_dex_file_locations_(),
288 compiler_driver_(nullptr),
289 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800290 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000291 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100292 vdex_size_(0u),
293 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100294 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100295 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100296 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000297 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000298 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000299 bss_roots_offset_(0u),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000300 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000301 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100302 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700303 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100304 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000305 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700306 size_dex_file_alignment_(0),
307 size_executable_offset_alignment_(0),
308 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700309 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700310 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100311 size_verifier_deps_(0),
312 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100313 size_quickening_info_(0),
314 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700315 size_interpreter_to_interpreter_bridge_(0),
316 size_interpreter_to_compiled_code_bridge_(0),
317 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800318 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700319 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700320 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700321 size_quick_to_interpreter_bridge_(0),
322 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100323 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700324 size_code_(0),
325 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100326 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100327 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700328 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700329 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700330 size_oat_dex_file_location_size_(0),
331 size_oat_dex_file_location_data_(0),
332 size_oat_dex_file_location_checksum_(0),
333 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000334 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000335 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000336 size_oat_lookup_table_alignment_(0),
337 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000338 size_oat_class_offsets_alignment_(0),
339 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700340 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700341 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700342 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100343 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000344 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700345 absolute_patch_locations_(),
346 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000347}
348
349bool OatWriter::AddDexFileSource(const char* filename,
350 const char* location,
351 CreateTypeLookupTable create_type_lookup_table) {
352 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
353 uint32_t magic;
354 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700355 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
356 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000357 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
358 return false;
359 } else if (IsDexMagic(magic)) {
360 // The file is open for reading, not writing, so it's OK to let the File destructor
361 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700362 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000363 oat_dex_files_.emplace_back(location,
364 DexFileSource(raw_dex_files_.back().get()),
365 create_type_lookup_table);
366 } else if (IsZipMagic(magic)) {
367 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
368 return false;
369 }
370 } else {
371 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
372 return false;
373 }
374 return true;
375}
376
377// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700378bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000379 const char* location,
380 CreateTypeLookupTable create_type_lookup_table) {
381 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
382 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700383 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000384 ZipArchive* zip_archive = zip_archives_.back().get();
385 if (zip_archive == nullptr) {
386 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
387 << error_msg;
388 return false;
389 }
390 for (size_t i = 0; ; ++i) {
391 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
392 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
393 if (entry == nullptr) {
394 break;
395 }
396 zipped_dex_files_.push_back(std::move(entry));
397 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
398 const char* full_location = zipped_dex_file_locations_.back().c_str();
399 oat_dex_files_.emplace_back(full_location,
400 DexFileSource(zipped_dex_files_.back().get()),
401 create_type_lookup_table);
402 }
403 if (zipped_dex_file_locations_.empty()) {
404 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
405 return false;
406 }
407 return true;
408}
409
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000410// Add dex file source(s) from a vdex file specified by a file handle.
411bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
412 const char* location,
413 CreateTypeLookupTable create_type_lookup_table) {
414 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
415 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000416 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000417 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
418 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000419 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
420 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000421 }
422 if (!DexFile::IsMagicValid(current_dex_data)) {
423 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
424 return false;
425 }
426 // We used `zipped_dex_file_locations_` to keep the strings in memory.
427 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
428 const char* full_location = zipped_dex_file_locations_.back().c_str();
429 oat_dex_files_.emplace_back(full_location,
430 DexFileSource(current_dex_data),
431 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000432 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000433 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000434
435 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
436 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
437 return false;
438 }
439
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000440 if (oat_dex_files_.empty()) {
441 LOG(ERROR) << "No dex files in vdex file created from " << location;
442 return false;
443 }
444 return true;
445}
446
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000447// Add dex file source from raw memory.
448bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
449 const char* location,
450 uint32_t location_checksum,
451 CreateTypeLookupTable create_type_lookup_table) {
452 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
453 if (data.size() < sizeof(DexFile::Header)) {
454 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
455 << data.size() << " File: " << location;
456 return false;
457 }
458 if (!ValidateDexFileHeader(data.data(), location)) {
459 return false;
460 }
461 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
462 if (data.size() < header->file_size_) {
463 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
464 << " file size from header: " << header->file_size_ << " File: " << location;
465 return false;
466 }
467
468 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
469 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
470 return true;
471}
472
473dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
474 dchecked_vector<const char*> locations;
475 locations.reserve(oat_dex_files_.size());
476 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
477 locations.push_back(oat_dex_file.GetLocation());
478 }
479 return locations;
480}
481
482bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100483 File* vdex_file,
484 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000485 InstructionSet instruction_set,
486 const InstructionSetFeatures* instruction_set_features,
487 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800488 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000489 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
491 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
492 CHECK(write_state_ == WriteState::kAddingDexFileSources);
493
David Brazdil7b49e6c2016-09-01 11:06:18 +0100494 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
495 if (!RecordOatDataOffset(oat_rodata)) {
496 return false;
497 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000498
499 std::unique_ptr<MemMap> dex_files_map;
500 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100501
502 // Initialize VDEX and OAT headers.
503 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000504 // Reserve space for Vdex header and checksums.
505 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100506 }
507 size_t oat_data_offset = InitOatHeader(instruction_set,
508 instruction_set_features,
509 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
510 key_value_store);
511 oat_size_ = InitOatDexFiles(oat_data_offset);
512
513 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
514
515 if (kIsVdexEnabled) {
516 std::unique_ptr<BufferedOutputStream> vdex_out(
517 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100518 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000519 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100520 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
521 return false;
522 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100523 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000524 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100525 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000526 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100527 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
528 return false;
529 }
530
531 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
532 // difficult because we're not using the OutputStream directly.
533 if (!oat_dex_files_.empty()) {
534 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
535 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
536 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000537 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000538
David Brazdil7b49e6c2016-09-01 11:06:18 +0100539 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000540 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
541 return false;
542 }
543
David Brazdil7b49e6c2016-09-01 11:06:18 +0100544 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000545 for (OatDexFile& oat_dex_file : oat_dex_files_) {
546 oat_dex_file.ReserveClassOffsets(this);
547 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100548
David Brazdil7b49e6c2016-09-01 11:06:18 +0100549 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000550 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
551 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000552 }
553
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000554 *opened_dex_files_map = std::move(dex_files_map);
555 *opened_dex_files = std::move(dex_files);
556 write_state_ = WriteState::kPrepareLayout;
557 return true;
558}
559
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100560void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000561 CHECK(write_state_ == WriteState::kPrepareLayout);
562
Vladimir Marko944da602016-02-19 12:27:55 +0000563 relative_patcher_ = relative_patcher;
564 SetMultiOatRelativePatcherAdjustment();
565
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000566 if (compiling_boot_image_) {
567 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800568 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100569 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000570 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100571
David Brazdil7b49e6c2016-09-01 11:06:18 +0100572 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800573 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000574 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800575 offset = InitOatClasses(offset);
576 }
577 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000578 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100579 offset = InitOatMaps(offset);
580 }
581 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000582 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800583 offset = InitOatCode(offset);
584 }
585 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000586 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800587 offset = InitOatCodeDexFiles(offset);
588 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100589 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700590
Vladimir Marko1998cd02017-01-13 13:02:58 +0000591 {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000592 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
593 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100594 }
595
Brian Carlstrome24fa612011-09-29 00:53:55 -0700596 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800597 if (compiling_boot_image_) {
598 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000599 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800600 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000601
602 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700603}
604
Ian Rogers0571d352011-11-03 19:51:38 -0700605OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700606}
607
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100608class OatWriter::DexMethodVisitor {
609 public:
610 DexMethodVisitor(OatWriter* writer, size_t offset)
611 : writer_(writer),
612 offset_(offset),
613 dex_file_(nullptr),
614 class_def_index_(DexFile::kDexNoIndex) {
615 }
616
617 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
618 DCHECK(dex_file_ == nullptr);
619 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
620 dex_file_ = dex_file;
621 class_def_index_ = class_def_index;
622 return true;
623 }
624
625 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
626
627 virtual bool EndClass() {
628 if (kIsDebugBuild) {
629 dex_file_ = nullptr;
630 class_def_index_ = DexFile::kDexNoIndex;
631 }
632 return true;
633 }
634
635 size_t GetOffset() const {
636 return offset_;
637 }
638
639 protected:
640 virtual ~DexMethodVisitor() { }
641
642 OatWriter* const writer_;
643
644 // The offset is usually advanced for each visited method by the derived class.
645 size_t offset_;
646
647 // The dex file and class def index are set in StartClass().
648 const DexFile* dex_file_;
649 size_t class_def_index_;
650};
651
652class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
653 public:
654 OatDexMethodVisitor(OatWriter* writer, size_t offset)
655 : DexMethodVisitor(writer, offset),
656 oat_class_index_(0u),
657 method_offsets_index_(0u) {
658 }
659
660 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
661 DexMethodVisitor::StartClass(dex_file, class_def_index);
662 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
663 method_offsets_index_ = 0u;
664 return true;
665 }
666
667 bool EndClass() {
668 ++oat_class_index_;
669 return DexMethodVisitor::EndClass();
670 }
671
672 protected:
673 size_t oat_class_index_;
674 size_t method_offsets_index_;
675};
676
677class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
678 public:
679 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
680 : DexMethodVisitor(writer, offset),
681 compiled_methods_(),
682 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000683 size_t num_classes = 0u;
684 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
685 num_classes += oat_dex_file.class_offsets_.size();
686 }
687 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100688 compiled_methods_.reserve(256u);
689 }
690
691 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
692 DexMethodVisitor::StartClass(dex_file, class_def_index);
693 compiled_methods_.clear();
694 num_non_null_compiled_methods_ = 0u;
695 return true;
696 }
697
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300698 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
699 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100700 // Fill in the compiled_methods_ array for methods that have a
701 // CompiledMethod. We track the number of non-null entries in
702 // num_non_null_compiled_methods_ since we only want to allocate
703 // OatMethodOffsets for the compiled methods.
704 uint32_t method_idx = it.GetMemberIndex();
705 CompiledMethod* compiled_method =
706 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
707 compiled_methods_.push_back(compiled_method);
708 if (compiled_method != nullptr) {
709 ++num_non_null_compiled_methods_;
710 }
711 return true;
712 }
713
714 bool EndClass() {
715 ClassReference class_ref(dex_file_, class_def_index_);
716 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
717 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700718 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100719 status = compiled_class->GetStatus();
720 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
Vladimir Marko72ab6842017-01-20 19:32:50 +0000721 // The oat class status is used only for verification of resolved classes,
722 // so use kStatusErrorResolved whether the class was resolved or unresolved
723 // during compile-time verification.
724 status = mirror::Class::kStatusErrorResolved;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100725 } else {
726 status = mirror::Class::kStatusNotReady;
727 }
728
Vladimir Marko49b0f452015-12-10 13:49:19 +0000729 writer_->oat_classes_.emplace_back(offset_,
730 compiled_methods_,
731 num_non_null_compiled_methods_,
732 status);
733 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100734 return DexMethodVisitor::EndClass();
735 }
736
737 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000738 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100739 size_t num_non_null_compiled_methods_;
740};
741
742class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
743 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100744 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100745 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100746 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
747 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100748 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100749 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
750 }
751
752 bool EndClass() {
753 OatDexMethodVisitor::EndClass();
754 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100755 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100756 }
757 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100758 }
759
760 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700761 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000762 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100763 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
764
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100765 if (it.GetMethodCodeItem() != nullptr) {
766 current_quickening_info_offset_ += sizeof(uint32_t);
767 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100768 if (compiled_method != nullptr) {
769 // Derived from CompiledMethod.
770 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100771
Vladimir Marko35831e82015-09-11 11:59:18 +0100772 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
773 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800774 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800775
David Srbecky009e2a62015-04-15 02:46:30 +0100776 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100777 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800778 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000779 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000780 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
781 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800782 // Duplicate methods, we want the same code for both of them so that the oat writer puts
783 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800784 } else {
785 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100786 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800787 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000788 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100789 quick_code_offset = dedupe_map_.GetOrCreate(
790 compiled_method,
791 [this, &deduped, compiled_method, &it, thumb_offset]() {
792 deduped = false;
793 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
794 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800795 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100796
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100797 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000798 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100799 // TODO: Should this be a hard failure?
800 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700801 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000802 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
803 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100804 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000805 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100806 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100808
Elliott Hughes956af0f2014-12-11 14:34:28 -0800809 // Update quick method header.
810 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
811 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700812 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700813 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800814 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
815 // to 0-offset and we need to adjust it by code_offset.
816 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100817 if (!compiled_method->GetQuickCode().empty()) {
818 // If the code is compiled, we write the offset of the stack map relative
819 // to the code,
820 if (vmap_table_offset != 0u) {
821 vmap_table_offset += code_offset;
822 DCHECK_LT(vmap_table_offset, code_offset);
823 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700824 if (method_info_offset != 0u) {
825 method_info_offset += code_offset;
826 DCHECK_LT(method_info_offset, code_offset);
827 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100828 } else {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700829 CHECK(compiled_method->GetMethodInfo().empty());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100830 if (kIsVdexEnabled) {
831 // We write the offset in the .vdex file.
832 DCHECK_EQ(vmap_table_offset, 0u);
833 vmap_table_offset = current_quickening_info_offset_;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700834 ArrayRef<const uint8_t> vmap_table = compiled_method->GetVmapTable();
835 current_quickening_info_offset_ += vmap_table.size() * sizeof(vmap_table.front());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100836 } else {
837 // We write the offset of the quickening info relative to the code.
838 vmap_table_offset += code_offset;
839 DCHECK_LT(vmap_table_offset, code_offset);
840 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800841 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800842 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
843 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
844 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100845 *method_header = OatQuickMethodHeader(vmap_table_offset,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700846 method_info_offset,
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100847 frame_size_in_bytes,
848 core_spill_mask,
849 fp_spill_mask,
850 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100851
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000852 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800853 // Update offsets. (Checksum is updated when writing.)
854 offset_ += sizeof(*method_header); // Method header is prepended before code.
855 offset_ += code_size;
856 // Record absolute patch locations.
857 if (!compiled_method->GetPatches().empty()) {
858 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
859 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000860 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100861 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100862 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000863 if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
864 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
865 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
866 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000867 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
868 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
869 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
870 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100871 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100872 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800873 }
Alex Light78382fa2014-06-06 15:45:32 -0700874
David Srbecky91cc06c2016-03-07 16:13:58 +0000875 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000876 // Exclude quickened dex methods (code_size == 0) since they have no native code.
877 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
878 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800879 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000880 debug::MethodDebugInfo info = debug::MethodDebugInfo();
881 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000882 info.dex_file = dex_file_;
883 info.class_def_index = class_def_index_;
884 info.dex_method_index = it.GetMemberIndex();
885 info.access_flags = it.GetMethodAccessFlags();
886 info.code_item = it.GetMethodCodeItem();
887 info.isa = compiled_method->GetInstructionSet();
888 info.deduped = deduped;
889 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
890 info.is_optimized = method_header->IsOptimized();
891 info.is_code_address_text_relative = true;
892 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
893 info.code_size = code_size;
894 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
895 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
896 info.cfi = compiled_method->GetCFIInfo();
897 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100898 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100899
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100900 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
901 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
902 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 ++method_offsets_index_;
904 }
905
906 return true;
907 }
908
909 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000910 struct CodeOffsetsKeyComparator {
911 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100912 // Code is deduplicated by CompilerDriver, compare only data pointers.
913 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
914 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000915 }
916 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100917 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
918 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000919 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700920 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
921 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
922 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100923 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
924 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000925 }
926 return false;
927 }
928 };
929
David Srbecky009e2a62015-04-15 02:46:30 +0100930 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
931 const ClassDataItemIterator& it,
932 uint32_t thumb_offset) {
933 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100934 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100935 offset_ += CodeAlignmentSize(offset_, *compiled_method);
936 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100937 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
938 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
939 }
940
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941 // Deduplication is already done on a pointer basis by the compiler driver,
942 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100943 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100944
David Srbecky009e2a62015-04-15 02:46:30 +0100945 // Cache of compiler's --debuggable option.
946 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100947
948 // Offset in the vdex file for the quickening info.
949 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100950};
951
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
953 public:
954 InitMapMethodVisitor(OatWriter* writer, size_t offset)
955 : OatDexMethodVisitor(writer, offset) {
956 }
957
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700958 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700959 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000960 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100961 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
962
963 if (compiled_method != nullptr) {
964 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100965 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
966 // be in the vdex file.
967 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700968 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100970 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
971 uint32_t map_size = map.size() * sizeof(map[0]);
972 if (map_size != 0u) {
973 size_t offset = dedupe_map_.GetOrCreate(
974 map.data(),
975 [this, map_size]() {
976 uint32_t new_offset = offset_;
977 offset_ += map_size;
978 return new_offset;
979 });
980 // Code offset is not initialized yet, so set the map offset to 0u-offset.
981 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700982 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100983 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100984 }
985 ++method_offsets_index_;
986 }
987
988 return true;
989 }
990
991 private:
992 // Deduplication is already done on a pointer basis by the compiler driver,
993 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100994 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100995};
996
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700997class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
998 public:
999 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1000
1001 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
1002 REQUIRES_SHARED(Locks::mutator_lock_) {
1003 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1004 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1005
1006 if (compiled_method != nullptr) {
1007 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1008 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1009 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1010 const uint32_t map_size = map.size() * sizeof(map[0]);
1011 if (map_size != 0u) {
1012 size_t offset = dedupe_map_.GetOrCreate(
1013 map.data(),
1014 [this, map_size]() {
1015 uint32_t new_offset = offset_;
1016 offset_ += map_size;
1017 return new_offset;
1018 });
1019 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1020 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1021 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1022 }
1023 ++method_offsets_index_;
1024 }
1025
1026 return true;
1027 }
1028
1029 private:
1030 // Deduplication is already done on a pointer basis by the compiler driver,
1031 // so we can simply compare the pointers to find out if things are duplicated.
1032 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1033};
1034
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001035class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1036 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001037 InitImageMethodVisitor(OatWriter* writer,
1038 size_t offset,
1039 const std::vector<const DexFile*>* dex_files)
Jeff Haoc7d11882015-02-03 15:08:39 -08001040 : OatDexMethodVisitor(writer, offset),
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001041 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1042 dex_files_(dex_files),
1043 class_linker_(Runtime::Current()->GetClassLinker()) {
1044 }
1045
1046 // Handle copied methods here. Copy pointer to quick code from
1047 // an origin method to a copied method only if they are
1048 // in the same oat file. If the origin and the copied methods are
1049 // in different oat files don't touch the copied method.
1050 // References to other oat files are not supported yet.
1051 bool StartClass(const DexFile* dex_file, size_t class_def_index)
1052 REQUIRES_SHARED(Locks::mutator_lock_) {
1053 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1054 // Skip classes that are not in the image.
1055 if (!IsImageClass()) {
1056 return true;
1057 }
1058 ScopedObjectAccessUnchecked soa(Thread::Current());
1059 StackHandleScope<1> hs(soa.Self());
1060 Handle<mirror::DexCache> dex_cache = hs.NewHandle(
1061 class_linker_->FindDexCache(Thread::Current(), *dex_file));
1062 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1063 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1064 if (klass != nullptr) {
1065 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1066 // Find origin method. Declaring class and dex_method_idx
1067 // in the copied method should be the same as in the origin
1068 // method.
1069 mirror::Class* declaring_class = method.GetDeclaringClass();
1070 ArtMethod* origin = declaring_class->FindDeclaredVirtualMethod(
1071 declaring_class->GetDexCache(),
1072 method.GetDexMethodIndex(),
1073 pointer_size_);
1074 CHECK(origin != nullptr);
1075 if (IsInOatFile(&declaring_class->GetDexFile())) {
1076 const void* code_ptr =
1077 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1078 if (code_ptr == nullptr) {
1079 methods_to_process_.push_back(std::make_pair(&method, origin));
1080 } else {
1081 method.SetEntryPointFromQuickCompiledCodePtrSize(
1082 code_ptr, pointer_size_);
1083 }
1084 }
1085 }
1086 }
1087 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001088 }
1089
1090 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001091 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001092 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001093 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001094 return true;
1095 }
1096
Vladimir Marko49b0f452015-12-10 13:49:19 +00001097 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001098 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1099
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001100 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001101 if (compiled_method != nullptr) {
1102 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1103 offsets = oat_class->method_offsets_[method_offsets_index_];
1104 ++method_offsets_index_;
1105 }
1106
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001107 // Unchecked as we hold mutator_lock_ on entry.
1108 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001109 StackHandleScope<1> hs(soa.Self());
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001110 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker_->FindDexCache(
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001111 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112 ArtMethod* method;
1113 if (writer_->HasBootImage()) {
1114 const InvokeType invoke_type = it.GetMethodInvokeType(
1115 dex_file_->GetClassDef(class_def_index_));
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001116 method = class_linker_->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 *dex_file_,
1118 it.GetMemberIndex(),
1119 dex_cache,
1120 ScopedNullHandle<mirror::ClassLoader>(),
1121 nullptr,
1122 invoke_type);
1123 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001124 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001125 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126 soa.Self()->AssertPendingException();
1127 mirror::Throwable* exc = soa.Self()->GetException();
1128 std::string dump = exc->Dump();
1129 LOG(FATAL) << dump;
1130 UNREACHABLE();
1131 }
1132 } else {
1133 // Should already have been resolved by the compiler, just peek into the dex cache.
1134 // It may not be resolved if the class failed to verify, in this case, don't set the
1135 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001136 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(),
1137 class_linker_->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001138 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001139 if (method != nullptr &&
1140 compiled_method != nullptr &&
1141 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001142 method->SetEntryPointFromQuickCompiledCodePtrSize(
1143 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1144 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001145
1146 return true;
1147 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001148
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001149 // Check whether current class is image class
1150 bool IsImageClass() {
1151 const DexFile::TypeId& type_id =
1152 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1153 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1154 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1155 }
1156
1157 // Check whether specified dex file is in the compiled oat file.
1158 bool IsInOatFile(const DexFile* dex_file) {
1159 return ContainsElement(*dex_files_, dex_file);
1160 }
1161
1162 // Assign a pointer to quick code for copied methods
1163 // not handled in the method StartClass
1164 void Postprocess() {
1165 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1166 ArtMethod* method = p.first;
1167 ArtMethod* origin = p.second;
1168 const void* code_ptr =
1169 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1170 if (code_ptr != nullptr) {
1171 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1172 }
1173 }
1174 }
1175
Jeff Haoc7d11882015-02-03 15:08:39 -08001176 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001177 const PointerSize pointer_size_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001178 const std::vector<const DexFile*>* dex_files_;
1179 ClassLinker* const class_linker_;
1180 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001181};
1182
1183class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1184 public:
1185 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001186 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001187 : OatDexMethodVisitor(writer, relative_offset),
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001188 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001189 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001190 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001191 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001192 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001193 class_linker_(Runtime::Current()->GetClassLinker()),
1194 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001195 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001196 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001197 // If we're creating the image, the address space must be ready so that we can apply patches.
1198 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001199 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001200 }
1201
Vladimir Markof4da6752014-08-01 19:04:18 +01001202 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001203 }
1204
1205 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001206 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001207 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1208 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001209 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001210 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001211 }
1212 return true;
1213 }
1214
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001215 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001216 bool result = OatDexMethodVisitor::EndClass();
1217 if (oat_class_index_ == writer_->oat_classes_.size()) {
1218 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001219 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001220 if (UNLIKELY(offset_ == 0u)) {
1221 PLOG(ERROR) << "Failed to write final relative call thunks";
1222 result = false;
1223 }
1224 }
1225 return result;
1226 }
1227
1228 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001229 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001230 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001231 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1232
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001233 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001234 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001235 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001236 size_t file_offset = file_offset_;
1237 OutputStream* out = out_;
1238
Vladimir Marko35831e82015-09-11 11:59:18 +01001239 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1240 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001241
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001242 // Deduplicate code arrays.
1243 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1244 if (method_offsets.code_offset_ > offset_) {
1245 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1246 if (offset_ == 0u) {
1247 ReportWriteFailure("relative call thunk", it);
1248 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001249 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001250 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1251 if (alignment_size != 0) {
1252 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001253 ReportWriteFailure("code alignment padding", it);
1254 return false;
1255 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001256 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001257 DCHECK_OFFSET_();
1258 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001259 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001260 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1261 DCHECK_EQ(method_offsets.code_offset_,
1262 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001263 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001264 const OatQuickMethodHeader& method_header =
1265 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001266 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001267 ReportWriteFailure("method header", it);
1268 return false;
1269 }
1270 writer_->size_method_header_ += sizeof(method_header);
1271 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001272 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001273
1274 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001275 patched_code_.assign(quick_code.begin(), quick_code.end());
1276 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001277 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001278 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001279 switch (patch.GetType()) {
1280 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001281 // NOTE: Relative calls across oat files are not supported.
1282 uint32_t target_offset = GetTargetOffset(patch);
1283 writer_->relative_patcher_->PatchCall(&patched_code_,
1284 literal_offset,
1285 offset_ + literal_offset,
1286 target_offset);
1287 break;
1288 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001289 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001290 uint32_t target_offset = GetDexCacheOffset(patch);
1291 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1292 patch,
1293 offset_ + literal_offset,
1294 target_offset);
1295 break;
1296 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001297 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001298 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1299 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1300 patch,
1301 offset_ + literal_offset,
1302 target_offset);
1303 break;
1304 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001305 case LinkerPatch::Type::kStringBssEntry: {
1306 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1307 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1308 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1309 patch,
1310 offset_ + literal_offset,
1311 target_offset);
1312 break;
1313 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001314 case LinkerPatch::Type::kTypeRelative: {
1315 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1316 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1317 patch,
1318 offset_ + literal_offset,
1319 target_offset);
1320 break;
1321 }
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001322 case LinkerPatch::Type::kTypeBssEntry: {
1323 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1324 uint32_t target_offset = writer_->bss_type_entries_.Get(ref);
1325 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1326 patch,
1327 offset_ + literal_offset,
1328 target_offset);
1329 break;
1330 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001331 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001332 uint32_t target_offset = GetTargetOffset(patch);
1333 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1334 break;
1335 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001336 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001337 ArtMethod* method = GetTargetMethod(patch);
1338 PatchMethodAddress(&patched_code_, literal_offset, method);
1339 break;
1340 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001341 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001342 mirror::String* string = GetTargetString(patch);
1343 PatchObjectAddress(&patched_code_, literal_offset, string);
1344 break;
1345 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001346 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001347 mirror::Class* type = GetTargetType(patch);
1348 PatchObjectAddress(&patched_code_, literal_offset, type);
1349 break;
1350 }
1351 default: {
Richard Uhlerc52f3032017-03-02 13:45:45 +00001352 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001353 break;
1354 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001355 }
1356 }
1357 }
1358
Vladimir Markoe079e212016-05-25 12:49:49 +01001359 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001360 ReportWriteFailure("method code", it);
1361 return false;
1362 }
1363 writer_->size_code_ += code_size;
1364 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001365 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001366 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001367 ++method_offsets_index_;
1368 }
1369
1370 return true;
1371 }
1372
1373 private:
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001374 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001375 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001376 const size_t file_offset_;
1377 const ScopedObjectAccess soa_;
1378 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001379 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001380 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001381 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001382
1383 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1384 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001385 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001386 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001387
Mathieu Chartiere401d142015-04-22 13:56:20 -07001388 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001389 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001390 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001391 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001392 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1393 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001394 ArtMethod* method = dex_cache->GetResolvedMethod(
1395 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001396 CHECK(method != nullptr);
1397 return method;
1398 }
1399
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001400 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001401 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1402 // If there's no new compiled code, either we're compiling an app and the target method
1403 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001404 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001405 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001406 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001407 PointerSize size =
1408 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001409 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1410 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001411 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001412 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1413 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1414 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1415 target_offset = PointerToLowMemUInt32(oat_code_offset);
1416 } else {
1417 target_offset = target->IsNative()
1418 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1419 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1420 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001421 }
1422 return target_offset;
1423 }
1424
Vladimir Markocd556b02017-02-03 11:47:34 +00001425 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001426 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001427 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001428 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001429 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1430 }
1431
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001432 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001433 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001434 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001435 ObjPtr<mirror::Class> type =
1436 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001437 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001438 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001439 }
1440
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001441 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001442 ScopedObjectAccessUnchecked soa(Thread::Current());
1443 StackHandleScope<1> hs(soa.Self());
1444 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1445 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1446 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1447 patch.TargetStringIndex(),
1448 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001449 DCHECK(string != nullptr);
1450 DCHECK(writer_->HasBootImage() ||
1451 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1452 return string;
1453 }
1454
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001455 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001456 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001457 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1458 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1459 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1460 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001461 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001462 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001463 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1464 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001465 }
1466 }
1467
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001468 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001469 DCHECK(writer_->HasBootImage());
1470 object = writer_->image_writer_->GetImageAddress(object);
1471 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1472 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1473 // TODO: Clean up offset types. The target offset must be treated as signed.
1474 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1475 }
1476
Vladimir Markof4da6752014-08-01 19:04:18 +01001477 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001478 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001479 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001480 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001481 } else {
1482 // NOTE: We're using linker patches for app->boot references when the image can
1483 // be relocated and therefore we need to emit .oat_patches. We're not using this
1484 // for app->app references, so check that the object is in the image space.
1485 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001486 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001487 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001488 uint32_t address = PointerToLowMemUInt32(object);
1489 DCHECK_LE(offset + 4, code->size());
1490 uint8_t* data = &(*code)[offset];
1491 data[0] = address & 0xffu;
1492 data[1] = (address >> 8) & 0xffu;
1493 data[2] = (address >> 16) & 0xffu;
1494 data[3] = (address >> 24) & 0xffu;
1495 }
1496
Mathieu Chartiere401d142015-04-22 13:56:20 -07001497 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001498 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001499 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001500 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001501 } else if (kIsDebugBuild) {
1502 // NOTE: We're using linker patches for app->boot references when the image can
1503 // be relocated and therefore we need to emit .oat_patches. We're not using this
1504 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001505 std::vector<gc::space::ImageSpace*> image_spaces =
1506 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1507 bool contains_method = false;
1508 for (gc::space::ImageSpace* image_space : image_spaces) {
1509 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1510 contains_method |=
1511 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1512 }
1513 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001514 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001515 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001516 uint32_t address = PointerToLowMemUInt32(method);
1517 DCHECK_LE(offset + 4, code->size());
1518 uint8_t* data = &(*code)[offset];
1519 data[0] = address & 0xffu;
1520 data[1] = (address >> 8) & 0xffu;
1521 data[2] = (address >> 16) & 0xffu;
1522 data[3] = (address >> 24) & 0xffu;
1523 }
1524
Vladimir Markof4da6752014-08-01 19:04:18 +01001525 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001526 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001527 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001528 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001529 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1530 // TODO: Clean up offset types.
1531 // The target_offset must be treated as signed for cross-oat patching.
1532 const void* target = reinterpret_cast<const void*>(
1533 writer_->image_writer_->GetOatDataBegin(oat_index) +
1534 static_cast<int32_t>(target_offset));
1535 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001536 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001537 DCHECK_LE(offset + 4, code->size());
1538 uint8_t* data = &(*code)[offset];
1539 data[0] = address & 0xffu;
1540 data[1] = (address >> 8) & 0xffu;
1541 data[2] = (address >> 16) & 0xffu;
1542 data[3] = (address >> 24) & 0xffu;
1543 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001544};
1545
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001546class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1547 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001548 WriteMapMethodVisitor(OatWriter* writer,
1549 OutputStream* out,
1550 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001551 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001552 : OatDexMethodVisitor(writer, relative_offset),
1553 out_(out),
1554 file_offset_(file_offset) {
1555 }
1556
1557 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001558 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001559 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1560
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001561 if (compiled_method != nullptr) { // i.e. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001562 size_t file_offset = file_offset_;
1563 OutputStream* out = out_;
1564
Mingyao Yang063fc772016-08-02 11:02:54 -07001565 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001566 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001567 ++method_offsets_index_;
1568
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001569 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1570 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1571 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001572 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001573
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001574 // If vdex is enabled, only emit the map for compiled code. The quickening info
1575 // is emitted in the vdex already.
1576 if (map_offset != 0u &&
1577 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001578 // Transform map_offset to actual oat data offset.
1579 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1580 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001581 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001582
1583 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1584 size_t map_size = map.size() * sizeof(map[0]);
1585 if (map_offset == offset_) {
1586 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001587 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001588 ReportWriteFailure(it);
1589 return false;
1590 }
1591 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001592 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001593 }
1594 DCHECK_OFFSET_();
1595 }
1596
1597 return true;
1598 }
1599
1600 private:
1601 OutputStream* const out_;
1602 size_t const file_offset_;
1603
1604 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001605 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001606 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001607 }
1608};
1609
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001610class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
1611 public:
1612 WriteMethodInfoVisitor(OatWriter* writer,
1613 OutputStream* out,
1614 const size_t file_offset,
1615 size_t relative_offset)
1616 : OatDexMethodVisitor(writer, relative_offset),
1617 out_(out),
1618 file_offset_(file_offset) {}
1619
1620 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
1621 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1622 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1623
1624 if (compiled_method != nullptr) { // i.e. not an abstract method
1625 size_t file_offset = file_offset_;
1626 OutputStream* out = out_;
1627 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
1628 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
1629 ++method_offsets_index_;
1630 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
1631 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
1632 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
1633 << dex_file_->PrettyMethod(it.GetMemberIndex());
1634 if (map_offset != 0u) {
1635 // Transform map_offset to actual oat data offset.
1636 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1637 DCHECK_NE(map_offset, 0u);
1638 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
1639
1640 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1641 size_t map_size = map.size() * sizeof(map[0]);
1642 if (map_offset == offset_) {
1643 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
1644 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
1645 ReportWriteFailure(it);
1646 return false;
1647 }
1648 offset_ += map_size;
1649 }
1650 }
1651 DCHECK_OFFSET_();
1652 }
1653
1654 return true;
1655 }
1656
1657 private:
1658 OutputStream* const out_;
1659 size_t const file_offset_;
1660
1661 void ReportWriteFailure(const ClassDataItemIterator& it) {
1662 PLOG(ERROR) << "Failed to write map for "
1663 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1664 }
1665};
1666
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001667// Visit all methods from all classes in all dex files with the specified visitor.
1668bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1669 for (const DexFile* dex_file : *dex_files_) {
1670 const size_t class_def_count = dex_file->NumClassDefs();
1671 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1672 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1673 return false;
1674 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001675 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1676 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1677 const uint8_t* class_data = dex_file->GetClassData(class_def);
1678 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1679 ClassDataItemIterator it(*dex_file, class_data);
1680 while (it.HasNextStaticField()) {
1681 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001682 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001683 while (it.HasNextInstanceField()) {
1684 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001685 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001686 size_t class_def_method_index = 0u;
1687 while (it.HasNextDirectMethod()) {
1688 if (!visitor->VisitMethod(class_def_method_index, it)) {
1689 return false;
1690 }
1691 ++class_def_method_index;
1692 it.Next();
1693 }
1694 while (it.HasNextVirtualMethod()) {
1695 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1696 return false;
1697 }
1698 ++class_def_method_index;
1699 it.Next();
1700 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001701 }
1702 }
1703 if (UNLIKELY(!visitor->EndClass())) {
1704 return false;
1705 }
1706 }
1707 }
1708 return true;
1709}
1710
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001711size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1712 const InstructionSetFeatures* instruction_set_features,
1713 uint32_t num_dex_files,
1714 SafeMap<std::string, std::string>* key_value_store) {
1715 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1716 oat_header_.reset(OatHeader::Create(instruction_set,
1717 instruction_set_features,
1718 num_dex_files,
1719 key_value_store));
1720 size_oat_header_ += sizeof(OatHeader);
1721 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001722 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001723}
1724
1725size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001726 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1727 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001728 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001729 oat_dex_file.offset_ = offset;
1730 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001731 }
1732 return offset;
1733}
1734
Brian Carlstrom389efb02012-01-11 12:06:26 -08001735size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001736 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001737 InitOatClassesMethodVisitor visitor(this, offset);
1738 bool success = VisitDexMethods(&visitor);
1739 CHECK(success);
1740 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001741
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001742 // Update oat_dex_files_.
1743 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001744 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1745 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001746 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001747 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001748 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001749 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001750 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001751 CHECK(oat_class_it == oat_classes_.end());
1752
1753 return offset;
1754}
1755
1756size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001757 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1758 return offset;
1759 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001760 {
1761 InitMapMethodVisitor visitor(this, offset);
1762 bool success = VisitDexMethods(&visitor);
1763 DCHECK(success);
1764 offset = visitor.GetOffset();
1765 }
1766 {
1767 InitMethodInfoVisitor visitor(this, offset);
1768 bool success = VisitDexMethods(&visitor);
1769 DCHECK(success);
1770 offset = visitor.GetOffset();
1771 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001772 return offset;
1773}
1774
1775size_t OatWriter::InitOatCode(size_t offset) {
1776 // calculate the offsets within OatHeader to executable code
1777 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001778 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001779 // required to be on a new page boundary
1780 offset = RoundUp(offset, kPageSize);
1781 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001782 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001783 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001784 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001785
Ian Rogers848871b2013-08-05 10:56:33 -07001786 #define DO_TRAMPOLINE(field, fn_name) \
1787 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001788 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1789 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001790 (field) = compiler_driver_->Create ## fn_name(); \
1791 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001792
Ian Rogers848871b2013-08-05 10:56:33 -07001793 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001794 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001795 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001796 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1797 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001798
Ian Rogers848871b2013-08-05 10:56:33 -07001799 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001800 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001801 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1802 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1803 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001804 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001805 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001806 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001807 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001808 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001809 return offset;
1810}
1811
1812size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001813 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1814 return offset;
1815 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001816 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1817 bool success = VisitDexMethods(&code_visitor);
1818 DCHECK(success);
1819 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001820
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001821 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001822 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001823 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001824 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001825 DCHECK(success);
1826 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001827 }
Logan Chien8b977d32012-02-21 19:14:55 +08001828
Brian Carlstrome24fa612011-09-29 00:53:55 -07001829 return offset;
1830}
1831
Vladimir Markoaad75c62016-10-03 08:46:48 +00001832void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00001833 if (HasBootImage()) {
1834 DCHECK(bss_string_entries_.empty());
1835 if (bss_type_entries_.empty()) {
1836 // Nothing to put to the .bss section.
1837 return;
1838 }
1839 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001840
1841 // Allocate space for app dex cache arrays in the .bss section.
1842 bss_start_ = RoundUp(oat_size_, kPageSize);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001843 bss_size_ = 0u;
Vladimir Marko1998cd02017-01-13 13:02:58 +00001844 if (!HasBootImage()) {
1845 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1846 for (const DexFile* dex_file : *dex_files_) {
1847 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1848 DexCacheArraysLayout layout(pointer_size, dex_file);
1849 bss_size_ += layout.Size();
1850 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001851 }
1852
1853 bss_roots_offset_ = bss_size_;
1854
Vladimir Marko6bec91c2017-01-09 15:03:12 +00001855 // Prepare offsets for .bss Class entries.
1856 for (auto& entry : bss_type_entries_) {
1857 DCHECK_EQ(entry.second, 0u);
1858 entry.second = bss_start_ + bss_size_;
1859 bss_size_ += sizeof(GcRoot<mirror::Class>);
1860 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001861 // Prepare offsets for .bss String entries.
1862 for (auto& entry : bss_string_entries_) {
1863 DCHECK_EQ(entry.second, 0u);
1864 entry.second = bss_start_ + bss_size_;
1865 bss_size_ += sizeof(GcRoot<mirror::String>);
1866 }
1867}
1868
David Srbeckybc90fd02015-04-22 19:40:27 +01001869bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001870 CHECK(write_state_ == WriteState::kWriteRoData);
1871
Vladimir Markoe079e212016-05-25 12:49:49 +01001872 // Wrap out to update checksum with each write.
1873 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1874 out = &checksum_updating_out;
1875
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001876 if (!WriteClassOffsets(out)) {
1877 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001878 return false;
1879 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001880
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001881 if (!WriteClasses(out)) {
1882 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001883 return false;
1884 }
1885
Vladimir Markof4da6752014-08-01 19:04:18 +01001886 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001887 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001888 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001889 return false;
1890 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001891 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001892 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001893 relative_offset = WriteMaps(out, file_offset, relative_offset);
1894 if (relative_offset == 0) {
1895 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1896 return false;
1897 }
1898
David Srbeckybc90fd02015-04-22 19:40:27 +01001899 // Write padding.
1900 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1901 relative_offset += size_executable_offset_alignment_;
1902 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1903 size_t expected_file_offset = file_offset + relative_offset;
1904 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1905 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1906 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1907 return 0;
1908 }
1909 DCHECK_OFFSET();
1910
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001911 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001912 return true;
1913}
1914
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001915class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1916 public:
1917 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1918 : DexMethodVisitor(writer, offset),
1919 out_(out),
1920 written_bytes_(0u) {}
1921
1922 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1923 const ClassDataItemIterator& it) {
1924 if (it.GetMethodCodeItem() == nullptr) {
1925 // No CodeItem. Native or abstract method.
1926 return true;
1927 }
1928
1929 uint32_t method_idx = it.GetMemberIndex();
1930 CompiledMethod* compiled_method =
1931 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1932
1933 uint32_t length = 0;
1934 const uint8_t* data = nullptr;
1935 // VMap only contains quickening info if this method is not compiled.
1936 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1937 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1938 data = map.data();
1939 length = map.size() * sizeof(map.front());
1940 }
1941
1942 if (!out_->WriteFully(&length, sizeof(length)) ||
1943 !out_->WriteFully(data, length)) {
1944 PLOG(ERROR) << "Failed to write quickening info for "
1945 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1946 return false;
1947 }
1948 offset_ += sizeof(length) + length;
1949 written_bytes_ += sizeof(length) + length;
1950 return true;
1951 }
1952
1953 size_t GetNumberOfWrittenBytes() const {
1954 return written_bytes_;
1955 }
1956
1957 private:
1958 OutputStream* const out_;
1959 size_t written_bytes_;
1960};
1961
1962bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1963 if (!kIsVdexEnabled) {
1964 return true;
1965 }
1966
1967 size_t initial_offset = vdex_size_;
1968 size_t start_offset = RoundUp(initial_offset, 4u);
1969
1970 vdex_size_ = start_offset;
1971 vdex_quickening_info_offset_ = vdex_size_;
1972 size_quickening_info_alignment_ = start_offset - initial_offset;
1973
1974 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1975 if (actual_offset != static_cast<off_t>(start_offset)) {
1976 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1977 << " Expected: " << start_offset
1978 << " Output: " << vdex_out->GetLocation();
1979 return false;
1980 }
1981
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001982 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1983 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1984 if (!VisitDexMethods(&visitor)) {
1985 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1986 return false;
1987 }
1988
1989 if (!vdex_out->Flush()) {
1990 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1991 << " File: " << vdex_out->GetLocation();
1992 return false;
1993 }
1994 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1995 } else {
1996 // We know we did not quicken.
1997 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001998 }
1999
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002000 vdex_size_ += size_quickening_info_;
2001 return true;
2002}
2003
David Brazdil5d5a36b2016-09-14 15:34:10 +01002004bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
2005 if (!kIsVdexEnabled) {
2006 return true;
2007 }
2008
2009 if (verifier_deps == nullptr) {
2010 // Nothing to write. Record the offset, but no need
2011 // for alignment.
2012 vdex_verifier_deps_offset_ = vdex_size_;
2013 return true;
2014 }
2015
2016 size_t initial_offset = vdex_size_;
2017 size_t start_offset = RoundUp(initial_offset, 4u);
2018
2019 vdex_size_ = start_offset;
2020 vdex_verifier_deps_offset_ = vdex_size_;
2021 size_verifier_deps_alignment_ = start_offset - initial_offset;
2022
2023 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2024 if (actual_offset != static_cast<off_t>(start_offset)) {
2025 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2026 << " Expected: " << start_offset
2027 << " Output: " << vdex_out->GetLocation();
2028 return false;
2029 }
2030
2031 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002032 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002033
2034 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2035 PLOG(ERROR) << "Failed to write verifier deps."
2036 << " File: " << vdex_out->GetLocation();
2037 return false;
2038 }
2039 if (!vdex_out->Flush()) {
2040 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2041 << " File: " << vdex_out->GetLocation();
2042 return false;
2043 }
2044
2045 size_verifier_deps_ = buffer.size();
2046 vdex_size_ += size_verifier_deps_;
2047 return true;
2048}
2049
David Srbeckybc90fd02015-04-22 19:40:27 +01002050bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002051 CHECK(write_state_ == WriteState::kWriteText);
2052
Vladimir Markoe079e212016-05-25 12:49:49 +01002053 // Wrap out to update checksum with each write.
2054 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2055 out = &checksum_updating_out;
2056
Vladimir Marko944da602016-02-19 12:27:55 +00002057 SetMultiOatRelativePatcherAdjustment();
2058
David Srbeckybc90fd02015-04-22 19:40:27 +01002059 const size_t file_offset = oat_data_offset_;
2060 size_t relative_offset = oat_header_->GetExecutableOffset();
2061 DCHECK_OFFSET();
2062
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002063 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002064 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002065 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002066 return false;
2067 }
2068
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002069 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2070 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002071 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002072 return false;
2073 }
2074
Vladimir Markof4da6752014-08-01 19:04:18 +01002075 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002076 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002077 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2078 return false;
2079 }
2080
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002081 if (kIsDebugBuild) {
2082 uint32_t size_total = 0;
2083 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002084 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2085 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002086
David Brazdil7b49e6c2016-09-01 11:06:18 +01002087 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002088 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002089 DO_STAT(size_dex_file_alignment_);
2090 DO_STAT(size_executable_offset_alignment_);
2091 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002092 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002093 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002094 DO_STAT(size_verifier_deps_);
2095 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002096 DO_STAT(size_quickening_info_);
2097 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002098 DO_STAT(size_interpreter_to_interpreter_bridge_);
2099 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2100 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002101 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002102 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002103 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002104 DO_STAT(size_quick_to_interpreter_bridge_);
2105 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002106 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002107 DO_STAT(size_code_);
2108 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002109 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002110 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002111 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002112 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002113 DO_STAT(size_oat_dex_file_location_size_);
2114 DO_STAT(size_oat_dex_file_location_data_);
2115 DO_STAT(size_oat_dex_file_location_checksum_);
2116 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002117 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002118 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002119 DO_STAT(size_oat_lookup_table_alignment_);
2120 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002121 DO_STAT(size_oat_class_offsets_alignment_);
2122 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002123 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002124 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002125 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002126 DO_STAT(size_oat_class_method_offsets_);
2127 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002128
David Brazdil7b49e6c2016-09-01 11:06:18 +01002129 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2130
2131 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2132 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002133 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002134
David Brazdil7b49e6c2016-09-01 11:06:18 +01002135 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2136 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002137
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002138 write_state_ = WriteState::kWriteHeader;
2139 return true;
2140}
2141
2142bool OatWriter::WriteHeader(OutputStream* out,
2143 uint32_t image_file_location_oat_checksum,
2144 uintptr_t image_file_location_oat_begin,
2145 int32_t image_patch_delta) {
2146 CHECK(write_state_ == WriteState::kWriteHeader);
2147
2148 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2149 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002150 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002151 CHECK_EQ(image_patch_delta, 0);
2152 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2153 } else {
2154 CHECK_ALIGNED(image_patch_delta, kPageSize);
2155 oat_header_->SetImagePatchDelta(image_patch_delta);
2156 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002157 oat_header_->UpdateChecksumWithHeaderData();
2158
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002159 const size_t file_offset = oat_data_offset_;
2160
2161 off_t current_offset = out->Seek(0, kSeekCurrent);
2162 if (current_offset == static_cast<off_t>(-1)) {
2163 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2164 return false;
2165 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002166 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002167 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2168 return false;
2169 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002170 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002171
2172 // Flush all other data before writing the header.
2173 if (!out->Flush()) {
2174 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2175 return false;
2176 }
2177 // Write the header.
2178 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002179 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002180 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2181 return false;
2182 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002183 // Flush the header data.
2184 if (!out->Flush()) {
2185 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002186 return false;
2187 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002188
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002189 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2190 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2191 return false;
2192 }
2193 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2194
2195 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002196 return true;
2197}
2198
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002199bool OatWriter::WriteClassOffsets(OutputStream* out) {
2200 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2201 if (oat_dex_file.class_offsets_offset_ != 0u) {
2202 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
2203 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
2204 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2205 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
2206 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00002207 return false;
2208 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002209 if (!oat_dex_file.WriteClassOffsets(this, out)) {
2210 return false;
2211 }
2212 }
2213 }
2214 return true;
2215}
2216
2217bool OatWriter::WriteClasses(OutputStream* out) {
2218 for (OatClass& oat_class : oat_classes_) {
2219 if (!oat_class.Write(this, out, oat_data_offset_)) {
2220 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
2221 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00002222 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002223 }
2224 return true;
2225}
2226
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002227size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002228 {
2229 size_t vmap_tables_offset = relative_offset;
2230 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2231 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2232 return 0;
2233 }
2234 relative_offset = visitor.GetOffset();
2235 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002236 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002237 {
2238 size_t method_infos_offset = relative_offset;
2239 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
2240 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2241 return 0;
2242 }
2243 relative_offset = visitor.GetOffset();
2244 size_method_info_ = relative_offset - method_infos_offset;
2245 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002246
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002247 return relative_offset;
2248}
2249
2250size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002251 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002252 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002253
Ian Rogers848871b2013-08-05 10:56:33 -07002254 #define DO_TRAMPOLINE(field) \
2255 do { \
2256 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2257 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002258 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002259 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002260 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002261 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002262 return false; \
2263 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002264 size_ ## field += (field)->size(); \
2265 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002266 DCHECK_OFFSET(); \
2267 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002268
Ian Rogers848871b2013-08-05 10:56:33 -07002269 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002270 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002271 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002272 DO_TRAMPOLINE(quick_resolution_trampoline_);
2273 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2274 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002275 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002276 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002277}
2278
Ian Rogers3d504072014-03-01 09:16:49 -08002279size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002280 const size_t file_offset,
2281 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002282 #define VISIT(VisitorType) \
2283 do { \
2284 VisitorType visitor(this, out, file_offset, relative_offset); \
2285 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2286 return 0; \
2287 } \
2288 relative_offset = visitor.GetOffset(); \
2289 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002290
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002291 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002292
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002293 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002294
Vladimir Markob163bb72015-03-31 21:49:49 +01002295 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2296 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2297 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2298
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002299 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002300}
2301
Vladimir Marko944da602016-02-19 12:27:55 +00002302bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002303 // Get the elf file offset of the oat file.
2304 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2305 if (raw_file_offset == static_cast<off_t>(-1)) {
2306 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2307 return false;
2308 }
2309 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2310 return true;
2311}
2312
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002313bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2314 // Read the dex file header and perform minimal verification.
2315 uint8_t raw_header[sizeof(DexFile::Header)];
2316 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2317 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2318 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2319 return false;
2320 }
2321 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2322 return false;
2323 }
2324
2325 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2326 oat_dex_file->dex_file_size_ = header->file_size_;
2327 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2328 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2329 return true;
2330}
2331
2332bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2333 if (!DexFile::IsMagicValid(raw_header)) {
2334 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2335 return false;
2336 }
2337 if (!DexFile::IsVersionValid(raw_header)) {
2338 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2339 return false;
2340 }
2341 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2342 if (header->file_size_ < sizeof(DexFile::Header)) {
2343 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2344 << " File: " << location;
2345 return false;
2346 }
2347 return true;
2348}
2349
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002350bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002351 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002352
David Brazdil7b49e6c2016-09-01 11:06:18 +01002353 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002354
2355 // Write dex files.
2356 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002357 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002358 return false;
2359 }
2360 }
2361
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002362 CloseSources();
2363 return true;
2364}
2365
2366void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2368 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2369 }
2370 zipped_dex_files_.clear();
2371 zip_archives_.clear();
2372 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002373}
2374
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002375bool OatWriter::WriteDexFile(OutputStream* out,
2376 File* file,
2377 OatDexFile* oat_dex_file,
2378 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002379 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002380 return false;
2381 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002382 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002383 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002384 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2385 return false;
2386 }
2387 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002388 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002389 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002390 return false;
2391 }
2392 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002393 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002394 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002395 return false;
2396 }
2397 } else {
2398 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002399 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002400 return false;
2401 }
2402 }
2403
2404 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002405 if (kIsVdexEnabled) {
2406 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2407 vdex_size_ += oat_dex_file->dex_file_size_;
2408 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002409 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002410 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2411 oat_size_ += oat_dex_file->dex_file_size_;
2412 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002413 size_dex_file_ += oat_dex_file->dex_file_size_;
2414 return true;
2415}
2416
2417bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2418 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002419 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2420 size_t start_offset = RoundUp(initial_offset, 4);
2421 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2422 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002423
2424 // Seek to the start of the dex file and flush any pending operations in the stream.
2425 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002426 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2427 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002428 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002429 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002430 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2431 return false;
2432 }
2433 if (!out->Flush()) {
2434 PLOG(ERROR) << "Failed to flush before writing dex file."
2435 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2436 return false;
2437 }
2438 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002439 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002440 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002441 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002442 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2443 return false;
2444 }
2445
David Brazdil7b49e6c2016-09-01 11:06:18 +01002446 if (kIsVdexEnabled) {
2447 vdex_size_ = start_offset;
2448 } else {
2449 oat_size_ = start_offset;
2450 }
2451 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002452 return true;
2453}
2454
Jeff Hao608f2ce2016-10-19 11:17:11 -07002455bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2456 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2457 std::string error_msg;
2458 std::string location(oat_dex_file->GetLocation());
2459 std::unique_ptr<const DexFile> dex_file;
2460 if (oat_dex_file->source_.IsZipEntry()) {
2461 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2462 std::unique_ptr<MemMap> mem_map(
2463 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08002464 if (mem_map == nullptr) {
2465 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
2466 return false;
2467 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002468 dex_file = DexFile::Open(location,
2469 zip_entry->GetCrc32(),
2470 std::move(mem_map),
2471 /* verify */ true,
2472 /* verify_checksum */ true,
2473 &error_msg);
Nicolas Geoffray97fa9922017-03-09 13:13:25 +00002474 } else {
2475 CHECK(oat_dex_file->source_.IsRawFile())
2476 << static_cast<size_t>(oat_dex_file->source_.GetType());
Jeff Hao608f2ce2016-10-19 11:17:11 -07002477 File* raw_file = oat_dex_file->source_.GetRawFile();
2478 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2479 }
Jeff Haode197542017-02-03 10:48:13 -08002480 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08002481 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08002482 return false;
2483 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002484 Options options;
2485 options.output_to_memmap_ = true;
2486 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2487 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2488 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002489 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002490 return false;
2491 }
2492 // Set the checksum of the new oat dex file to be the original file's checksum.
2493 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2494 return true;
2495}
2496
David Brazdil7b49e6c2016-09-01 11:06:18 +01002497bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002498 File* file,
2499 OatDexFile* oat_dex_file,
2500 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002501 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2502 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002503
2504 // Extract the dex file and get the extracted size.
2505 std::string error_msg;
2506 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2507 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2508 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2509 return false;
2510 }
2511 if (file->Flush() != 0) {
2512 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2513 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2514 return false;
2515 }
2516 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2517 if (extracted_end == static_cast<off_t>(-1)) {
2518 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2519 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2520 return false;
2521 }
2522 if (extracted_end < static_cast<off_t>(start_offset)) {
2523 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2524 << " Start: " << start_offset
2525 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2526 return false;
2527 }
2528 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2529 if (extracted_size < sizeof(DexFile::Header)) {
2530 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2531 << extracted_size << " File: " << oat_dex_file->GetLocation();
2532 return false;
2533 }
2534
2535 // Read the dex file header and extract required data to OatDexFile.
2536 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2537 if (actual_offset != static_cast<off_t>(start_offset)) {
2538 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2539 << " Expected: " << start_offset
2540 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2541 return false;
2542 }
2543 if (!ReadDexFileHeader(file, oat_dex_file)) {
2544 return false;
2545 }
2546 if (extracted_size < oat_dex_file->dex_file_size_) {
2547 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2548 << " file size from header: " << oat_dex_file->dex_file_size_
2549 << " File: " << oat_dex_file->GetLocation();
2550 return false;
2551 }
2552
2553 // Override the checksum from header with the CRC from ZIP entry.
2554 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2555
2556 // Seek both file and stream to the end offset.
2557 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2558 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2559 if (actual_offset != static_cast<off_t>(end_offset)) {
2560 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2561 << " Expected: " << end_offset
2562 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2563 return false;
2564 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002565 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002566 if (actual_offset != static_cast<off_t>(end_offset)) {
2567 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2568 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2569 return false;
2570 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002571 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002572 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2573 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2574 return false;
2575 }
2576
2577 // If we extracted more than the size specified in the header, truncate the file.
2578 if (extracted_size > oat_dex_file->dex_file_size_) {
2579 if (file->SetLength(end_offset) != 0) {
2580 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002581 << " File: " << oat_dex_file->GetLocation()
2582 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002583 return false;
2584 }
2585 }
2586
2587 return true;
2588}
2589
David Brazdil7b49e6c2016-09-01 11:06:18 +01002590bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002591 File* file,
2592 OatDexFile* oat_dex_file,
2593 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002594 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2595 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002596
2597 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2598 if (input_offset != static_cast<off_t>(0)) {
2599 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2600 << " Expected: 0"
2601 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2602 return false;
2603 }
2604 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2605 return false;
2606 }
2607
2608 // Copy the input dex file using sendfile().
2609 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2610 PLOG(ERROR) << "Failed to copy dex file to oat file."
2611 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2612 return false;
2613 }
2614 if (file->Flush() != 0) {
2615 PLOG(ERROR) << "Failed to flush dex file."
2616 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2617 return false;
2618 }
2619
2620 // Check file position and seek the stream to the end offset.
2621 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2622 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2623 if (actual_offset != static_cast<off_t>(end_offset)) {
2624 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2625 << " Expected: " << end_offset
2626 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2627 return false;
2628 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002629 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002630 if (actual_offset != static_cast<off_t>(end_offset)) {
2631 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2632 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2633 return false;
2634 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002635 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002636 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2637 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2638 return false;
2639 }
2640
2641 return true;
2642}
2643
David Brazdil7b49e6c2016-09-01 11:06:18 +01002644bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002645 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002646 const uint8_t* dex_file,
2647 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002648 // Note: The raw data has already been checked to contain the header
2649 // and all the data that the header specifies as the file size.
2650 DCHECK(dex_file != nullptr);
2651 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2652 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2653
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002654 if (update_input_vdex) {
2655 // The vdex already contains the dex code, no need to write it again.
2656 } else {
2657 if (!out->WriteFully(dex_file, header->file_size_)) {
2658 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2659 << " to " << out->GetLocation();
2660 return false;
2661 }
2662 if (!out->Flush()) {
2663 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2664 << " File: " << oat_dex_file->GetLocation();
2665 return false;
2666 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002667 }
2668
2669 // Update dex file size and resize class offsets in the OatDexFile.
2670 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002671 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002672 oat_dex_file->dex_file_size_ = header->file_size_;
2673 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2674 return true;
2675}
2676
2677bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2678 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2679
David Brazdil181e1cc2016-09-01 16:38:47 +00002680 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2681 if (initial_offset == static_cast<off_t>(-1)) {
2682 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2683 return false;
2684 }
2685
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002686 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2687 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2688 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2689 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2690 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2691 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2692 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2693 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2694 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2695 return false;
2696 }
2697
2698 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2699 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2700
2701 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2702 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2703
2704 // Write OatDexFile.
2705 if (!oat_dex_file->Write(this, rodata)) {
2706 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2707 return false;
2708 }
2709 }
2710
David Brazdil181e1cc2016-09-01 16:38:47 +00002711 // Seek back to the initial position.
2712 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2713 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2714 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2715 return false;
2716 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002717
David Brazdilb92ba622016-09-01 16:00:30 +00002718 return true;
2719}
2720
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002721bool OatWriter::OpenDexFiles(
2722 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002723 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002724 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2725 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2726 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2727
2728 if (oat_dex_files_.empty()) {
2729 // Nothing to do.
2730 return true;
2731 }
2732
2733 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002734 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2735
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002736 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002737 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2738 length,
2739 PROT_READ | PROT_WRITE,
2740 MAP_SHARED,
2741 file->Fd(),
2742 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2743 /* low_4gb */ false,
2744 file->GetPath().c_str(),
2745 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002746 if (dex_files_map == nullptr) {
2747 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2748 << " error: " << error_msg;
2749 return false;
2750 }
2751 std::vector<std::unique_ptr<const DexFile>> dex_files;
2752 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2753 // Make sure no one messed with input files while we were copying data.
2754 // At the very least we need consistent file size and number of class definitions.
2755 const uint8_t* raw_dex_file =
2756 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2757 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2758 // Note: ValidateDexFileHeader() already logged an error message.
2759 LOG(ERROR) << "Failed to verify written dex file header!"
2760 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2761 << " ~ " << static_cast<const void*>(raw_dex_file);
2762 return false;
2763 }
2764 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2765 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2766 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2767 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2768 << " Output: " << file->GetPath();
2769 return false;
2770 }
2771 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2772 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2773 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2774 << " Output: " << file->GetPath();
2775 return false;
2776 }
2777
2778 // Now, open the dex file.
2779 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2780 oat_dex_file.dex_file_size_,
2781 oat_dex_file.GetLocation(),
2782 oat_dex_file.dex_file_location_checksum_,
2783 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002784 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002785 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002786 &error_msg));
2787 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002788 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2789 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002790 return false;
2791 }
2792 }
2793
2794 *opened_dex_files_map = std::move(dex_files_map);
2795 *opened_dex_files = std::move(dex_files);
2796 return true;
2797}
2798
2799bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002800 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002801 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2802 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2803
David Brazdil7b49e6c2016-09-01 11:06:18 +01002804 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2805 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2806 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2807 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2808 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2809 return false;
2810 }
2811
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002812 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2813 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2814 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002815 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2816
2817 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2818 oat_dex_file->class_offsets_.empty()) {
2819 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002820 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002821
2822 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2823 if (table_size == 0u) {
2824 continue;
2825 }
2826
2827 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002828 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002829 const DexFile& dex_file = *opened_dex_files[i];
2830 {
2831 std::unique_ptr<TypeLookupTable> type_lookup_table =
2832 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2833 type_lookup_table_oat_dex_files_.push_back(
2834 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2835 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2836 }
2837 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002838
2839 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002840 size_t initial_offset = oat_size_;
2841 size_t rodata_offset = RoundUp(initial_offset, 4);
2842 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002843
2844 if (padding_size != 0u) {
2845 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002846 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002847 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2848 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002849 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002850 return false;
2851 }
2852 }
2853
2854 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002855 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002856 DCHECK_EQ(table_size, table->RawDataLength());
2857
David Brazdil7b49e6c2016-09-01 11:06:18 +01002858 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002859 PLOG(ERROR) << "Failed to write lookup table."
2860 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002861 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002862 return false;
2863 }
2864
2865 oat_dex_file->lookup_table_offset_ = rodata_offset;
2866
David Brazdil7b49e6c2016-09-01 11:06:18 +01002867 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002868 size_oat_lookup_table_ += table_size;
2869 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002870 }
2871
David Brazdil7b49e6c2016-09-01 11:06:18 +01002872 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002873 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002874 << " File: " << oat_rodata->GetLocation();
2875 return false;
2876 }
2877
2878 return true;
2879}
2880
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002881bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002882 if (!kIsVdexEnabled) {
2883 return true;
2884 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002885 // Write checksums
2886 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2887 if (actual_offset != sizeof(VdexFile::Header)) {
2888 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2889 << " File: " << vdex_out->GetLocation();
2890 return false;
2891 }
2892
2893 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2894 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2895 if (!vdex_out->WriteFully(
2896 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2897 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2898 << vdex_out->GetLocation();
2899 return false;
2900 }
2901 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2902 }
2903
2904 // Write header.
2905 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002906 if (actual_offset != 0) {
2907 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2908 << " File: " << vdex_out->GetLocation();
2909 return false;
2910 }
2911
David Brazdil5d5a36b2016-09-14 15:34:10 +01002912 DCHECK_NE(vdex_dex_files_offset_, 0u);
2913 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2914
2915 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002916 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2917 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002918
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002919 VdexFile::Header vdex_header(oat_dex_files_.size(),
2920 dex_section_size,
2921 verifier_deps_section_size,
2922 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002923 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2924 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002925 return false;
2926 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002927 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002928
David Brazdil5d5a36b2016-09-14 15:34:10 +01002929 if (!vdex_out->Flush()) {
2930 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2931 << " File: " << vdex_out->GetLocation();
2932 return false;
2933 }
2934
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002935 return true;
2936}
2937
Vladimir Markof4da6752014-08-01 19:04:18 +01002938bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2939 static const uint8_t kPadding[] = {
2940 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2941 };
2942 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002943 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002944 return false;
2945 }
2946 size_code_alignment_ += aligned_code_delta;
2947 return true;
2948}
2949
Vladimir Marko944da602016-02-19 12:27:55 +00002950void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2951 DCHECK(dex_files_ != nullptr);
2952 DCHECK(relative_patcher_ != nullptr);
2953 DCHECK_NE(oat_data_offset_, 0u);
2954 if (image_writer_ != nullptr && !dex_files_->empty()) {
2955 // The oat data begin may not be initialized yet but the oat file offset is ready.
2956 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2957 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2958 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002959 }
2960}
2961
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002962OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2963 DexFileSource source,
2964 CreateTypeLookupTable create_type_lookup_table)
2965 : source_(source),
2966 create_type_lookup_table_(create_type_lookup_table),
2967 dex_file_size_(0),
2968 offset_(0),
2969 dex_file_location_size_(strlen(dex_file_location)),
2970 dex_file_location_data_(dex_file_location),
2971 dex_file_location_checksum_(0u),
2972 dex_file_offset_(0u),
2973 class_offsets_offset_(0u),
2974 lookup_table_offset_(0u),
2975 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002976}
2977
2978size_t OatWriter::OatDexFile::SizeOf() const {
2979 return sizeof(dex_file_location_size_)
2980 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002981 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002982 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002983 + sizeof(class_offsets_offset_)
2984 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002985}
2986
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002987void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2988 DCHECK_EQ(class_offsets_offset_, 0u);
2989 if (!class_offsets_.empty()) {
2990 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002991 size_t initial_offset = oat_writer->oat_size_;
2992 size_t offset = RoundUp(initial_offset, 4);
2993 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002994 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002995 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002996 }
2997}
2998
2999bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3000 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003001 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003002
Vladimir Markoe079e212016-05-25 12:49:49 +01003003 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003004 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003005 return false;
3006 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003007 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003008
Vladimir Markoe079e212016-05-25 12:49:49 +01003009 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003010 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003011 return false;
3012 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003013 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003014
Vladimir Markoe079e212016-05-25 12:49:49 +01003015 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003016 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003017 return false;
3018 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003019 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003020
Vladimir Markoe079e212016-05-25 12:49:49 +01003021 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003022 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003023 return false;
3024 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003025 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003026
Vladimir Markoe079e212016-05-25 12:49:49 +01003027 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003028 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3029 return false;
3030 }
3031 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3032
Vladimir Markoe079e212016-05-25 12:49:49 +01003033 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003034 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3035 return false;
3036 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003037 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003038
3039 return true;
3040}
3041
3042bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003043 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003044 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
3045 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003046 return false;
3047 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003048 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003049 return true;
3050}
3051
Brian Carlstromba150c32013-08-27 17:31:03 -07003052OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00003053 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07003054 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003055 mirror::Class::Status status)
3056 : compiled_methods_(compiled_methods) {
3057 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07003058 CHECK_LE(num_non_null_compiled_methods, num_methods);
3059
Brian Carlstrom265091e2013-01-30 14:08:26 -08003060 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07003061 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
3062
3063 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
3064 // apply when there are 0 methods, we just arbitrarily say that 0
3065 // methods means kOatClassNoneCompiled and that we won't use
3066 // kOatClassAllCompiled unless there is at least one compiled
3067 // method. This means in an interpretter only system, we can assert
3068 // that all classes are kOatClassNoneCompiled.
3069 if (num_non_null_compiled_methods == 0) {
3070 type_ = kOatClassNoneCompiled;
3071 } else if (num_non_null_compiled_methods == num_methods) {
3072 type_ = kOatClassAllCompiled;
3073 } else {
3074 type_ = kOatClassSomeCompiled;
3075 }
3076
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003077 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07003078 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01003079 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07003080
3081 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
3082 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003083 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07003084 method_bitmap_size_ = method_bitmap_->GetSizeOf();
3085 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
3086 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
3087 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003088 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07003089 method_bitmap_size_ = 0;
3090 }
3091
3092 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003093 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003094 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003095 oat_method_offsets_offsets_from_oat_class_[i] = 0;
3096 } else {
3097 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
3098 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
3099 if (type_ == kOatClassSomeCompiled) {
3100 method_bitmap_->SetBit(i);
3101 }
3102 }
3103 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003104}
3105
Brian Carlstrom265091e2013-01-30 14:08:26 -08003106size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
3107 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003108 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
3109 if (method_offset == 0) {
3110 return 0;
3111 }
3112 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003113}
3114
3115size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
3116 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003117 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08003118}
3119
3120size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003121 return sizeof(status_)
3122 + sizeof(type_)
3123 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
3124 + method_bitmap_size_
3125 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07003126}
3127
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003128bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08003129 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003130 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08003131 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01003132 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003133 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003134 return false;
3135 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003136 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003137
Vladimir Markoe079e212016-05-25 12:49:49 +01003138 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003139 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003140 return false;
3141 }
3142 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003143
Brian Carlstromba150c32013-08-27 17:31:03 -07003144 if (method_bitmap_size_ != 0) {
3145 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01003146 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003147 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003148 return false;
3149 }
3150 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003151
Vladimir Markoe079e212016-05-25 12:49:49 +01003152 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003153 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003154 return false;
3155 }
3156 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
3157 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003158
Vladimir Markoe079e212016-05-25 12:49:49 +01003159 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08003160 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003161 return false;
3162 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003163 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003164 return true;
3165}
3166
Brian Carlstrome24fa612011-09-29 00:53:55 -07003167} // namespace art