blob: 153aff40dc15eed461289697e990dbedd4c69ef6 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000027#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070030#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070031#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000032#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000033#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "dex_file-inl.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070036#include "dexlayout.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "driver/compiler_driver.h"
38#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010039#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030041#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010042#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010043#include "linker/buffered_output_stream.h"
44#include "linker/file_output_stream.h"
Vladimir Marko944da602016-02-19 12:27:55 +000045#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000046#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/array.h"
48#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010049#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010051#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070052#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070053#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030055#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010056#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010057#include "vdex_file.h"
jeffhaoec014232012-09-05 10:42:25 -070058#include "verifier/method_verifier.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010059#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000060#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070061
62namespace art {
63
Vladimir Marko9bdf1082016-01-21 12:15:52 +000064namespace { // anonymous namespace
65
66typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
67
68const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
69 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
70}
71
Vladimir Markoe079e212016-05-25 12:49:49 +010072class ChecksumUpdatingOutputStream : public OutputStream {
73 public:
74 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
75 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
76
77 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
78 oat_header_->UpdateChecksum(buffer, byte_count);
79 return out_->WriteFully(buffer, byte_count);
80 }
81
82 off_t Seek(off_t offset, Whence whence) OVERRIDE {
83 return out_->Seek(offset, whence);
84 }
85
86 bool Flush() OVERRIDE {
87 return out_->Flush();
88 }
89
90 private:
91 OutputStream* const out_;
92 OatHeader* const oat_header_;
93};
94
Vladimir Marko0c737df2016-08-01 16:33:16 +010095inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
96 // We want to align the code rather than the preheader.
97 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
98 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
99 return aligned_code_offset - unaligned_code_offset;
100}
101
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000102} // anonymous namespace
103
104// Defines the location of the raw dex file to write.
105class OatWriter::DexFileSource {
106 public:
107 explicit DexFileSource(ZipEntry* zip_entry)
108 : type_(kZipEntry), source_(zip_entry) {
109 DCHECK(source_ != nullptr);
110 }
111
112 explicit DexFileSource(File* raw_file)
113 : type_(kRawFile), source_(raw_file) {
114 DCHECK(source_ != nullptr);
115 }
116
117 explicit DexFileSource(const uint8_t* dex_file)
118 : type_(kRawData), source_(dex_file) {
119 DCHECK(source_ != nullptr);
120 }
121
122 bool IsZipEntry() const { return type_ == kZipEntry; }
123 bool IsRawFile() const { return type_ == kRawFile; }
124 bool IsRawData() const { return type_ == kRawData; }
125
126 ZipEntry* GetZipEntry() const {
127 DCHECK(IsZipEntry());
128 DCHECK(source_ != nullptr);
129 return static_cast<ZipEntry*>(const_cast<void*>(source_));
130 }
131
132 File* GetRawFile() const {
133 DCHECK(IsRawFile());
134 DCHECK(source_ != nullptr);
135 return static_cast<File*>(const_cast<void*>(source_));
136 }
137
138 const uint8_t* GetRawData() const {
139 DCHECK(IsRawData());
140 DCHECK(source_ != nullptr);
141 return static_cast<const uint8_t*>(source_);
142 }
143
144 void Clear() {
145 type_ = kNone;
146 source_ = nullptr;
147 }
148
149 private:
150 enum Type {
151 kNone,
152 kZipEntry,
153 kRawFile,
154 kRawData,
155 };
156
157 Type type_;
158 const void* source_;
159};
160
Vladimir Marko49b0f452015-12-10 13:49:19 +0000161class OatWriter::OatClass {
162 public:
163 OatClass(size_t offset,
164 const dchecked_vector<CompiledMethod*>& compiled_methods,
165 uint32_t num_non_null_compiled_methods,
166 mirror::Class::Status status);
167 OatClass(OatClass&& src) = default;
168 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
169 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
170 size_t SizeOf() const;
171 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
172
173 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
174 return compiled_methods_[class_def_method_index];
175 }
176
177 // Offset of start of OatClass from beginning of OatHeader. It is
178 // used to validate file position when writing.
179 size_t offset_;
180
181 // CompiledMethods for each class_def_method_index, or null if no method is available.
182 dchecked_vector<CompiledMethod*> compiled_methods_;
183
184 // Offset from OatClass::offset_ to the OatMethodOffsets for the
185 // class_def_method_index. If 0, it means the corresponding
186 // CompiledMethod entry in OatClass::compiled_methods_ should be
187 // null and that the OatClass::type_ should be kOatClassBitmap.
188 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
189
190 // Data to write.
191
192 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
193 int16_t status_;
194
195 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
196 uint16_t type_;
197
198 uint32_t method_bitmap_size_;
199
200 // bit vector indexed by ClassDef method index. When
201 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
202 // method has an OatMethodOffsets in methods_offsets_, otherwise
203 // the entry was ommited to save space. If OatClassType::type_ is
204 // not is kOatClassBitmap, the bitmap will be null.
205 std::unique_ptr<BitVector> method_bitmap_;
206
207 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
208 // present in the OatClass. Note that some may be missing if
209 // OatClass::compiled_methods_ contains null values (and
210 // oat_method_offsets_offsets_from_oat_class_ should contain 0
211 // values in this case).
212 dchecked_vector<OatMethodOffsets> method_offsets_;
213 dchecked_vector<OatQuickMethodHeader> method_headers_;
214
215 private:
216 size_t GetMethodOffsetsRawSize() const {
217 return method_offsets_.size() * sizeof(method_offsets_[0]);
218 }
219
220 DISALLOW_COPY_AND_ASSIGN(OatClass);
221};
222
223class OatWriter::OatDexFile {
224 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 OatDexFile(const char* dex_file_location,
226 DexFileSource source,
227 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000228 OatDexFile(OatDexFile&& src) = default;
229
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000230 const char* GetLocation() const {
231 return dex_file_location_data_;
232 }
233
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000234 void ReserveClassOffsets(OatWriter* oat_writer);
235
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000237 bool Write(OatWriter* oat_writer, OutputStream* out) const;
238 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
239
240 // The source of the dex file.
241 DexFileSource source_;
242
243 // Whether to create the type lookup table.
244 CreateTypeLookupTable create_type_lookup_table_;
245
246 // Dex file size. Initialized when writing the dex file.
247 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248
249 // Offset of start of OatDexFile from beginning of OatHeader. It is
250 // used to validate file position when writing.
251 size_t offset_;
252
253 // Data to write.
254 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000256 uint32_t dex_file_location_checksum_;
257 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000258 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000259 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000260
261 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000262 dchecked_vector<uint32_t> class_offsets_;
263
264 private:
265 size_t GetClassOffsetsRawSize() const {
266 return class_offsets_.size() * sizeof(class_offsets_[0]);
267 }
268
269 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
270};
271
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100272#define DCHECK_OFFSET() \
273 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
274 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
275
276#define DCHECK_OFFSET_() \
277 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
278 << "file_offset=" << file_offset << " offset_=" << offset_
279
Jeff Hao608f2ce2016-10-19 11:17:11 -0700280OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000281 : write_state_(WriteState::kAddingDexFileSources),
282 timings_(timings),
283 raw_dex_files_(),
284 zip_archives_(),
285 zipped_dex_files_(),
286 zipped_dex_file_locations_(),
287 compiler_driver_(nullptr),
288 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800289 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000290 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100291 vdex_size_(0u),
292 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100293 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100294 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100295 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000296 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000297 bss_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000298 bss_roots_offset_(0u),
299 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100300 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700301 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100302 size_vdex_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700303 size_dex_file_alignment_(0),
304 size_executable_offset_alignment_(0),
305 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700306 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700307 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100308 size_verifier_deps_(0),
309 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100310 size_quickening_info_(0),
311 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700312 size_interpreter_to_interpreter_bridge_(0),
313 size_interpreter_to_compiled_code_bridge_(0),
314 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800315 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700316 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700317 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700318 size_quick_to_interpreter_bridge_(0),
319 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100320 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700321 size_code_(0),
322 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100323 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100324 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700325 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700326 size_oat_dex_file_location_size_(0),
327 size_oat_dex_file_location_data_(0),
328 size_oat_dex_file_location_checksum_(0),
329 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000330 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000331 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000332 size_oat_lookup_table_alignment_(0),
333 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000334 size_oat_class_offsets_alignment_(0),
335 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700336 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700337 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700338 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100339 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000340 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700341 absolute_patch_locations_(),
342 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000343}
344
345bool OatWriter::AddDexFileSource(const char* filename,
346 const char* location,
347 CreateTypeLookupTable create_type_lookup_table) {
348 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
349 uint32_t magic;
350 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700351 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
352 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000353 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
354 return false;
355 } else if (IsDexMagic(magic)) {
356 // The file is open for reading, not writing, so it's OK to let the File destructor
357 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700358 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000359 oat_dex_files_.emplace_back(location,
360 DexFileSource(raw_dex_files_.back().get()),
361 create_type_lookup_table);
362 } else if (IsZipMagic(magic)) {
363 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
364 return false;
365 }
366 } else {
367 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
368 return false;
369 }
370 return true;
371}
372
373// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700374bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000375 const char* location,
376 CreateTypeLookupTable create_type_lookup_table) {
377 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
378 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700379 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000380 ZipArchive* zip_archive = zip_archives_.back().get();
381 if (zip_archive == nullptr) {
382 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
383 << error_msg;
384 return false;
385 }
386 for (size_t i = 0; ; ++i) {
387 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
388 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
389 if (entry == nullptr) {
390 break;
391 }
392 zipped_dex_files_.push_back(std::move(entry));
393 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
394 const char* full_location = zipped_dex_file_locations_.back().c_str();
395 oat_dex_files_.emplace_back(full_location,
396 DexFileSource(zipped_dex_files_.back().get()),
397 create_type_lookup_table);
398 }
399 if (zipped_dex_file_locations_.empty()) {
400 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
401 return false;
402 }
403 return true;
404}
405
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000406// Add dex file source(s) from a vdex file specified by a file handle.
407bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
408 const char* location,
409 CreateTypeLookupTable create_type_lookup_table) {
410 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
411 const uint8_t* current_dex_data = nullptr;
412 for (size_t i = 0; ; ++i) {
413 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
414 if (current_dex_data == nullptr) {
415 break;
416 }
417 if (!DexFile::IsMagicValid(current_dex_data)) {
418 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
419 return false;
420 }
421 // We used `zipped_dex_file_locations_` to keep the strings in memory.
422 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
423 const char* full_location = zipped_dex_file_locations_.back().c_str();
424 oat_dex_files_.emplace_back(full_location,
425 DexFileSource(current_dex_data),
426 create_type_lookup_table);
427 }
428 if (oat_dex_files_.empty()) {
429 LOG(ERROR) << "No dex files in vdex file created from " << location;
430 return false;
431 }
432 return true;
433}
434
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000435// Add dex file source from raw memory.
436bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
437 const char* location,
438 uint32_t location_checksum,
439 CreateTypeLookupTable create_type_lookup_table) {
440 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
441 if (data.size() < sizeof(DexFile::Header)) {
442 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
443 << data.size() << " File: " << location;
444 return false;
445 }
446 if (!ValidateDexFileHeader(data.data(), location)) {
447 return false;
448 }
449 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
450 if (data.size() < header->file_size_) {
451 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
452 << " file size from header: " << header->file_size_ << " File: " << location;
453 return false;
454 }
455
456 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
457 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
458 return true;
459}
460
461dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
462 dchecked_vector<const char*> locations;
463 locations.reserve(oat_dex_files_.size());
464 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
465 locations.push_back(oat_dex_file.GetLocation());
466 }
467 return locations;
468}
469
470bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100471 File* vdex_file,
472 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000473 InstructionSet instruction_set,
474 const InstructionSetFeatures* instruction_set_features,
475 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800476 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000477 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
478 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
479 CHECK(write_state_ == WriteState::kAddingDexFileSources);
480
David Brazdil7b49e6c2016-09-01 11:06:18 +0100481 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
482 if (!RecordOatDataOffset(oat_rodata)) {
483 return false;
484 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000485
486 std::unique_ptr<MemMap> dex_files_map;
487 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100488
489 // Initialize VDEX and OAT headers.
490 if (kIsVdexEnabled) {
491 size_vdex_header_ = sizeof(VdexFile::Header);
492 vdex_size_ = size_vdex_header_;
493 }
494 size_t oat_data_offset = InitOatHeader(instruction_set,
495 instruction_set_features,
496 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
497 key_value_store);
498 oat_size_ = InitOatDexFiles(oat_data_offset);
499
500 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
501
502 if (kIsVdexEnabled) {
503 std::unique_ptr<BufferedOutputStream> vdex_out(
504 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
505
506 // Write DEX files into VDEX, mmap and open them.
507 if (!WriteDexFiles(vdex_out.get(), vdex_file) ||
508 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
509 return false;
510 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100511 } else {
512 // Write DEX files into OAT, mmap and open them.
513 if (!WriteDexFiles(oat_rodata, vdex_file) ||
514 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
515 return false;
516 }
517
518 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
519 // difficult because we're not using the OutputStream directly.
520 if (!oat_dex_files_.empty()) {
521 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
522 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
523 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000525
David Brazdil7b49e6c2016-09-01 11:06:18 +0100526 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000527 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
528 return false;
529 }
530
David Brazdil7b49e6c2016-09-01 11:06:18 +0100531 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000532 for (OatDexFile& oat_dex_file : oat_dex_files_) {
533 oat_dex_file.ReserveClassOffsets(this);
534 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100535
David Brazdil7b49e6c2016-09-01 11:06:18 +0100536 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000537 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
538 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000539 }
540
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000541 *opened_dex_files_map = std::move(dex_files_map);
542 *opened_dex_files = std::move(dex_files);
543 write_state_ = WriteState::kPrepareLayout;
544 return true;
545}
546
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100547void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000548 CHECK(write_state_ == WriteState::kPrepareLayout);
549
Vladimir Marko944da602016-02-19 12:27:55 +0000550 relative_patcher_ = relative_patcher;
551 SetMultiOatRelativePatcherAdjustment();
552
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000553 if (compiling_boot_image_) {
554 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800555 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100556 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100558
David Brazdil7b49e6c2016-09-01 11:06:18 +0100559 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800560 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000561 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800562 offset = InitOatClasses(offset);
563 }
564 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000565 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100566 offset = InitOatMaps(offset);
567 }
568 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000569 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800570 offset = InitOatCode(offset);
571 }
572 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000573 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800574 offset = InitOatCodeDexFiles(offset);
575 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100576 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700577
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800578 if (!HasBootImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000579 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
580 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100581 }
582
Brian Carlstrome24fa612011-09-29 00:53:55 -0700583 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800584 if (compiling_boot_image_) {
585 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000586 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800587 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000588
589 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700590}
591
Ian Rogers0571d352011-11-03 19:51:38 -0700592OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700593}
594
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100595class OatWriter::DexMethodVisitor {
596 public:
597 DexMethodVisitor(OatWriter* writer, size_t offset)
598 : writer_(writer),
599 offset_(offset),
600 dex_file_(nullptr),
601 class_def_index_(DexFile::kDexNoIndex) {
602 }
603
604 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
605 DCHECK(dex_file_ == nullptr);
606 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
607 dex_file_ = dex_file;
608 class_def_index_ = class_def_index;
609 return true;
610 }
611
612 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
613
614 virtual bool EndClass() {
615 if (kIsDebugBuild) {
616 dex_file_ = nullptr;
617 class_def_index_ = DexFile::kDexNoIndex;
618 }
619 return true;
620 }
621
622 size_t GetOffset() const {
623 return offset_;
624 }
625
626 protected:
627 virtual ~DexMethodVisitor() { }
628
629 OatWriter* const writer_;
630
631 // The offset is usually advanced for each visited method by the derived class.
632 size_t offset_;
633
634 // The dex file and class def index are set in StartClass().
635 const DexFile* dex_file_;
636 size_t class_def_index_;
637};
638
639class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
640 public:
641 OatDexMethodVisitor(OatWriter* writer, size_t offset)
642 : DexMethodVisitor(writer, offset),
643 oat_class_index_(0u),
644 method_offsets_index_(0u) {
645 }
646
647 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
648 DexMethodVisitor::StartClass(dex_file, class_def_index);
649 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
650 method_offsets_index_ = 0u;
651 return true;
652 }
653
654 bool EndClass() {
655 ++oat_class_index_;
656 return DexMethodVisitor::EndClass();
657 }
658
659 protected:
660 size_t oat_class_index_;
661 size_t method_offsets_index_;
662};
663
664class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
665 public:
666 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
667 : DexMethodVisitor(writer, offset),
668 compiled_methods_(),
669 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000670 size_t num_classes = 0u;
671 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
672 num_classes += oat_dex_file.class_offsets_.size();
673 }
674 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100675 compiled_methods_.reserve(256u);
676 }
677
678 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
679 DexMethodVisitor::StartClass(dex_file, class_def_index);
680 compiled_methods_.clear();
681 num_non_null_compiled_methods_ = 0u;
682 return true;
683 }
684
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300685 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
686 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687 // Fill in the compiled_methods_ array for methods that have a
688 // CompiledMethod. We track the number of non-null entries in
689 // num_non_null_compiled_methods_ since we only want to allocate
690 // OatMethodOffsets for the compiled methods.
691 uint32_t method_idx = it.GetMemberIndex();
692 CompiledMethod* compiled_method =
693 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
694 compiled_methods_.push_back(compiled_method);
695 if (compiled_method != nullptr) {
696 ++num_non_null_compiled_methods_;
697 }
698 return true;
699 }
700
701 bool EndClass() {
702 ClassReference class_ref(dex_file_, class_def_index_);
703 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
704 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700705 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100706 status = compiled_class->GetStatus();
707 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
708 status = mirror::Class::kStatusError;
709 } else {
710 status = mirror::Class::kStatusNotReady;
711 }
712
Vladimir Marko49b0f452015-12-10 13:49:19 +0000713 writer_->oat_classes_.emplace_back(offset_,
714 compiled_methods_,
715 num_non_null_compiled_methods_,
716 status);
717 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 return DexMethodVisitor::EndClass();
719 }
720
721 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000722 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723 size_t num_non_null_compiled_methods_;
724};
725
726class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
727 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100728 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100729 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100730 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
731 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100732 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100733 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
734 }
735
736 bool EndClass() {
737 OatDexMethodVisitor::EndClass();
738 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100739 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100740 }
741 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100742 }
743
744 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700745 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000746 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100747 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
748
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100749 if (it.GetMethodCodeItem() != nullptr) {
750 current_quickening_info_offset_ += sizeof(uint32_t);
751 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100752 if (compiled_method != nullptr) {
753 // Derived from CompiledMethod.
754 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755
Vladimir Marko35831e82015-09-11 11:59:18 +0100756 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
757 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800758 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800759
David Srbecky009e2a62015-04-15 02:46:30 +0100760 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100761 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800762 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000763 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000764 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
765 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800766 // Duplicate methods, we want the same code for both of them so that the oat writer puts
767 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800768 } else {
769 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100770 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800771 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000772 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100773 quick_code_offset = dedupe_map_.GetOrCreate(
774 compiled_method,
775 [this, &deduped, compiled_method, &it, thumb_offset]() {
776 deduped = false;
777 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
778 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800779 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100780
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100781 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000782 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100783 // TODO: Should this be a hard failure?
784 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700785 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000786 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
787 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100788 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000789 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100790 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800791 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100792
Elliott Hughes956af0f2014-12-11 14:34:28 -0800793 // Update quick method header.
794 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
795 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800796 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Elliott Hughes956af0f2014-12-11 14:34:28 -0800797 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
798 // to 0-offset and we need to adjust it by code_offset.
799 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100800 if (!compiled_method->GetQuickCode().empty()) {
801 // If the code is compiled, we write the offset of the stack map relative
802 // to the code,
803 if (vmap_table_offset != 0u) {
804 vmap_table_offset += code_offset;
805 DCHECK_LT(vmap_table_offset, code_offset);
806 }
807 } else {
808 if (kIsVdexEnabled) {
809 // We write the offset in the .vdex file.
810 DCHECK_EQ(vmap_table_offset, 0u);
811 vmap_table_offset = current_quickening_info_offset_;
812 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
813 current_quickening_info_offset_ += map.size() * sizeof(map.front());
814 } else {
815 // We write the offset of the quickening info relative to the code.
816 vmap_table_offset += code_offset;
817 DCHECK_LT(vmap_table_offset, code_offset);
818 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800819 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800820 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
821 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
822 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100823 *method_header = OatQuickMethodHeader(vmap_table_offset,
824 frame_size_in_bytes,
825 core_spill_mask,
826 fp_spill_mask,
827 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100828
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000829 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800830 // Update offsets. (Checksum is updated when writing.)
831 offset_ += sizeof(*method_header); // Method header is prepended before code.
832 offset_ += code_size;
833 // Record absolute patch locations.
834 if (!compiled_method->GetPatches().empty()) {
835 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
836 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000837 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100838 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100839 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000840 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
841 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
842 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
843 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100844 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100845 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800846 }
Alex Light78382fa2014-06-06 15:45:32 -0700847
David Srbecky91cc06c2016-03-07 16:13:58 +0000848 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000849 // Exclude quickened dex methods (code_size == 0) since they have no native code.
850 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
851 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800852 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000853 debug::MethodDebugInfo info = debug::MethodDebugInfo();
854 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000855 info.dex_file = dex_file_;
856 info.class_def_index = class_def_index_;
857 info.dex_method_index = it.GetMemberIndex();
858 info.access_flags = it.GetMethodAccessFlags();
859 info.code_item = it.GetMethodCodeItem();
860 info.isa = compiled_method->GetInstructionSet();
861 info.deduped = deduped;
862 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
863 info.is_optimized = method_header->IsOptimized();
864 info.is_code_address_text_relative = true;
865 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
866 info.code_size = code_size;
867 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
868 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
869 info.cfi = compiled_method->GetCFIInfo();
870 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100871 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100872
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100873 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
874 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
875 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100876 ++method_offsets_index_;
877 }
878
879 return true;
880 }
881
882 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000883 struct CodeOffsetsKeyComparator {
884 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100885 // Code is deduplicated by CompilerDriver, compare only data pointers.
886 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
887 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000888 }
889 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100890 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
891 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000892 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100893 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
894 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000895 }
896 return false;
897 }
898 };
899
David Srbecky009e2a62015-04-15 02:46:30 +0100900 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
901 const ClassDataItemIterator& it,
902 uint32_t thumb_offset) {
903 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100904 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100905 offset_ += CodeAlignmentSize(offset_, *compiled_method);
906 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100907 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
908 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
909 }
910
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100911 // Deduplication is already done on a pointer basis by the compiler driver,
912 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100913 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100914
David Srbecky009e2a62015-04-15 02:46:30 +0100915 // Cache of compiler's --debuggable option.
916 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100917
918 // Offset in the vdex file for the quickening info.
919 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920};
921
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100922class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
923 public:
924 InitMapMethodVisitor(OatWriter* writer, size_t offset)
925 : OatDexMethodVisitor(writer, offset) {
926 }
927
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700928 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700929 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000930 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100931 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
932
933 if (compiled_method != nullptr) {
934 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100935 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
936 // be in the vdex file.
937 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
938 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100940 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
941 uint32_t map_size = map.size() * sizeof(map[0]);
942 if (map_size != 0u) {
943 size_t offset = dedupe_map_.GetOrCreate(
944 map.data(),
945 [this, map_size]() {
946 uint32_t new_offset = offset_;
947 offset_ += map_size;
948 return new_offset;
949 });
950 // Code offset is not initialized yet, so set the map offset to 0u-offset.
951 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
952 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
953 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100954 }
955 ++method_offsets_index_;
956 }
957
958 return true;
959 }
960
961 private:
962 // Deduplication is already done on a pointer basis by the compiler driver,
963 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100964 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100965};
966
967class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
968 public:
969 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800970 : OatDexMethodVisitor(writer, offset),
971 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100972 }
973
974 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700975 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800976 const DexFile::TypeId& type_id =
977 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
978 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
979 // Skip methods that are not in the image.
980 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
981 return true;
982 }
983
Vladimir Marko49b0f452015-12-10 13:49:19 +0000984 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100985 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
986
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800987 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100988 if (compiled_method != nullptr) {
989 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
990 offsets = oat_class->method_offsets_[method_offsets_index_];
991 ++method_offsets_index_;
992 }
993
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100994 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100995 // Unchecked as we hold mutator_lock_ on entry.
996 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800997 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700998 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
999 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001000 ArtMethod* method;
1001 if (writer_->HasBootImage()) {
1002 const InvokeType invoke_type = it.GetMethodInvokeType(
1003 dex_file_->GetClassDef(class_def_index_));
1004 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1005 *dex_file_,
1006 it.GetMemberIndex(),
1007 dex_cache,
1008 ScopedNullHandle<mirror::ClassLoader>(),
1009 nullptr,
1010 invoke_type);
1011 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001012 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001013 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001014 soa.Self()->AssertPendingException();
1015 mirror::Throwable* exc = soa.Self()->GetException();
1016 std::string dump = exc->Dump();
1017 LOG(FATAL) << dump;
1018 UNREACHABLE();
1019 }
1020 } else {
1021 // Should already have been resolved by the compiler, just peek into the dex cache.
1022 // It may not be resolved if the class failed to verify, in this case, don't set the
1023 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1024 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001025 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001026 if (method != nullptr &&
1027 compiled_method != nullptr &&
1028 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001029 method->SetEntryPointFromQuickCompiledCodePtrSize(
1030 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1031 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001032
1033 return true;
1034 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001035
1036 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001037 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001038};
1039
1040class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1041 public:
1042 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001043 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001044 : OatDexMethodVisitor(writer, relative_offset),
1045 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001046 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001047 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001048 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001049 class_linker_(Runtime::Current()->GetClassLinker()),
1050 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001051 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001052 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001053 // If we're creating the image, the address space must be ready so that we can apply patches.
1054 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001055 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001056 }
1057
Vladimir Markof4da6752014-08-01 19:04:18 +01001058 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001059 }
1060
1061 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001062 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001063 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1064 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001065 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001066 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001067 }
1068 return true;
1069 }
1070
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001071 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001072 bool result = OatDexMethodVisitor::EndClass();
1073 if (oat_class_index_ == writer_->oat_classes_.size()) {
1074 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001075 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001076 if (UNLIKELY(offset_ == 0u)) {
1077 PLOG(ERROR) << "Failed to write final relative call thunks";
1078 result = false;
1079 }
1080 }
1081 return result;
1082 }
1083
1084 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001085 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001086 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001087 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1088
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001089 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001090 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001091 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001092 size_t file_offset = file_offset_;
1093 OutputStream* out = out_;
1094
Vladimir Marko35831e82015-09-11 11:59:18 +01001095 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1096 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001097
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001098 // Deduplicate code arrays.
1099 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1100 if (method_offsets.code_offset_ > offset_) {
1101 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1102 if (offset_ == 0u) {
1103 ReportWriteFailure("relative call thunk", it);
1104 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001105 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001106 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1107 if (alignment_size != 0) {
1108 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001109 ReportWriteFailure("code alignment padding", it);
1110 return false;
1111 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001112 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001113 DCHECK_OFFSET_();
1114 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001115 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001116 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1117 DCHECK_EQ(method_offsets.code_offset_,
1118 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001119 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001120 const OatQuickMethodHeader& method_header =
1121 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001122 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001123 ReportWriteFailure("method header", it);
1124 return false;
1125 }
1126 writer_->size_method_header_ += sizeof(method_header);
1127 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001128 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001129
1130 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001131 patched_code_.assign(quick_code.begin(), quick_code.end());
1132 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001133 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001134 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001135 switch (patch.GetType()) {
1136 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001137 // NOTE: Relative calls across oat files are not supported.
1138 uint32_t target_offset = GetTargetOffset(patch);
1139 writer_->relative_patcher_->PatchCall(&patched_code_,
1140 literal_offset,
1141 offset_ + literal_offset,
1142 target_offset);
1143 break;
1144 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001145 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001146 uint32_t target_offset = GetDexCacheOffset(patch);
1147 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1148 patch,
1149 offset_ + literal_offset,
1150 target_offset);
1151 break;
1152 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001153 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001154 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1155 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1156 patch,
1157 offset_ + literal_offset,
1158 target_offset);
1159 break;
1160 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001161 case LinkerPatch::Type::kStringBssEntry: {
1162 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1163 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1164 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1165 patch,
1166 offset_ + literal_offset,
1167 target_offset);
1168 break;
1169 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001170 case LinkerPatch::Type::kTypeRelative: {
1171 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1172 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1173 patch,
1174 offset_ + literal_offset,
1175 target_offset);
1176 break;
1177 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001178 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001179 uint32_t target_offset = GetTargetOffset(patch);
1180 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1181 break;
1182 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001183 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001184 ArtMethod* method = GetTargetMethod(patch);
1185 PatchMethodAddress(&patched_code_, literal_offset, method);
1186 break;
1187 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001188 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001189 mirror::String* string = GetTargetString(patch);
1190 PatchObjectAddress(&patched_code_, literal_offset, string);
1191 break;
1192 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001193 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001194 mirror::Class* type = GetTargetType(patch);
1195 PatchObjectAddress(&patched_code_, literal_offset, type);
1196 break;
1197 }
1198 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001199 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001200 break;
1201 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001202 }
1203 }
1204 }
1205
Vladimir Markoe079e212016-05-25 12:49:49 +01001206 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001207 ReportWriteFailure("method code", it);
1208 return false;
1209 }
1210 writer_->size_code_ += code_size;
1211 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001212 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001213 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001214 ++method_offsets_index_;
1215 }
1216
1217 return true;
1218 }
1219
1220 private:
1221 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001222 const size_t file_offset_;
1223 const ScopedObjectAccess soa_;
1224 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001225 ClassLinker* const class_linker_;
1226 mirror::DexCache* dex_cache_;
1227 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001228
1229 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1230 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001231 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001232 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001233
Mathieu Chartiere401d142015-04-22 13:56:20 -07001234 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001235 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001236 MethodReference ref = patch.TargetMethod();
1237 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001238 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1239 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001240 ArtMethod* method = dex_cache->GetResolvedMethod(
1241 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001242 CHECK(method != nullptr);
1243 return method;
1244 }
1245
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001246 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001247 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1248 // If there's no new compiled code, either we're compiling an app and the target method
1249 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001250 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001251 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001252 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001253 PointerSize size =
1254 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001255 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1256 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001257 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001258 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1259 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1260 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1261 target_offset = PointerToLowMemUInt32(oat_code_offset);
1262 } else {
1263 target_offset = target->IsNative()
1264 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1265 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1266 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001267 }
1268 return target_offset;
1269 }
1270
Vladimir Marko052164a2016-04-27 13:54:18 +01001271 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001272 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001273 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001274 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001275 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1276 }
1277
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001278 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001279 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001280 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1281 CHECK(type != nullptr);
1282 return type;
1283 }
1284
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001285 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001286 ScopedObjectAccessUnchecked soa(Thread::Current());
1287 StackHandleScope<1> hs(soa.Self());
1288 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1289 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1290 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1291 patch.TargetStringIndex(),
1292 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001293 DCHECK(string != nullptr);
1294 DCHECK(writer_->HasBootImage() ||
1295 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1296 return string;
1297 }
1298
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001299 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001300 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001301 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1302 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1303 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1304 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001305 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001306 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001307 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1308 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001309 }
1310 }
1311
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001312 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001313 DCHECK(writer_->HasBootImage());
1314 object = writer_->image_writer_->GetImageAddress(object);
1315 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1316 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1317 // TODO: Clean up offset types. The target offset must be treated as signed.
1318 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1319 }
1320
Vladimir Markof4da6752014-08-01 19:04:18 +01001321 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001322 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001323 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001324 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001325 } else {
1326 // NOTE: We're using linker patches for app->boot references when the image can
1327 // be relocated and therefore we need to emit .oat_patches. We're not using this
1328 // for app->app references, so check that the object is in the image space.
1329 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001330 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001331 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001332 uint32_t address = PointerToLowMemUInt32(object);
1333 DCHECK_LE(offset + 4, code->size());
1334 uint8_t* data = &(*code)[offset];
1335 data[0] = address & 0xffu;
1336 data[1] = (address >> 8) & 0xffu;
1337 data[2] = (address >> 16) & 0xffu;
1338 data[3] = (address >> 24) & 0xffu;
1339 }
1340
Mathieu Chartiere401d142015-04-22 13:56:20 -07001341 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001342 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001343 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001344 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001345 } else if (kIsDebugBuild) {
1346 // NOTE: We're using linker patches for app->boot references when the image can
1347 // be relocated and therefore we need to emit .oat_patches. We're not using this
1348 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001349 std::vector<gc::space::ImageSpace*> image_spaces =
1350 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1351 bool contains_method = false;
1352 for (gc::space::ImageSpace* image_space : image_spaces) {
1353 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1354 contains_method |=
1355 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1356 }
1357 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001358 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001359 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001360 uint32_t address = PointerToLowMemUInt32(method);
1361 DCHECK_LE(offset + 4, code->size());
1362 uint8_t* data = &(*code)[offset];
1363 data[0] = address & 0xffu;
1364 data[1] = (address >> 8) & 0xffu;
1365 data[2] = (address >> 16) & 0xffu;
1366 data[3] = (address >> 24) & 0xffu;
1367 }
1368
Vladimir Markof4da6752014-08-01 19:04:18 +01001369 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001370 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001371 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001372 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001373 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1374 // TODO: Clean up offset types.
1375 // The target_offset must be treated as signed for cross-oat patching.
1376 const void* target = reinterpret_cast<const void*>(
1377 writer_->image_writer_->GetOatDataBegin(oat_index) +
1378 static_cast<int32_t>(target_offset));
1379 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001380 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001381 DCHECK_LE(offset + 4, code->size());
1382 uint8_t* data = &(*code)[offset];
1383 data[0] = address & 0xffu;
1384 data[1] = (address >> 8) & 0xffu;
1385 data[2] = (address >> 16) & 0xffu;
1386 data[3] = (address >> 24) & 0xffu;
1387 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001388};
1389
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001390class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1391 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001392 WriteMapMethodVisitor(OatWriter* writer,
1393 OutputStream* out,
1394 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001395 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001396 : OatDexMethodVisitor(writer, relative_offset),
1397 out_(out),
1398 file_offset_(file_offset) {
1399 }
1400
1401 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001402 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001403 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1404
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001405 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001406 size_t file_offset = file_offset_;
1407 OutputStream* out = out_;
1408
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001409 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1410 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001411 ++method_offsets_index_;
1412
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001413 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1414 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1415 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001416 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001417
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001418 // If vdex is enabled, only emit the map for compiled code. The quickening info
1419 // is emitted in the vdex already.
1420 if (map_offset != 0u &&
1421 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001422 // Transform map_offset to actual oat data offset.
1423 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1424 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001425 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001426
1427 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1428 size_t map_size = map.size() * sizeof(map[0]);
1429 if (map_offset == offset_) {
1430 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001431 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001432 ReportWriteFailure(it);
1433 return false;
1434 }
1435 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001436 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001437 }
1438 DCHECK_OFFSET_();
1439 }
1440
1441 return true;
1442 }
1443
1444 private:
1445 OutputStream* const out_;
1446 size_t const file_offset_;
1447
1448 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001449 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001450 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001451 }
1452};
1453
1454// Visit all methods from all classes in all dex files with the specified visitor.
1455bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1456 for (const DexFile* dex_file : *dex_files_) {
1457 const size_t class_def_count = dex_file->NumClassDefs();
1458 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1459 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1460 return false;
1461 }
1462 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001463 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001464 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001465 ClassDataItemIterator it(*dex_file, class_data);
1466 while (it.HasNextStaticField()) {
1467 it.Next();
1468 }
1469 while (it.HasNextInstanceField()) {
1470 it.Next();
1471 }
1472 size_t class_def_method_index = 0u;
1473 while (it.HasNextDirectMethod()) {
1474 if (!visitor->VisitMethod(class_def_method_index, it)) {
1475 return false;
1476 }
1477 ++class_def_method_index;
1478 it.Next();
1479 }
1480 while (it.HasNextVirtualMethod()) {
1481 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1482 return false;
1483 }
1484 ++class_def_method_index;
1485 it.Next();
1486 }
1487 }
1488 if (UNLIKELY(!visitor->EndClass())) {
1489 return false;
1490 }
1491 }
1492 }
1493 return true;
1494}
1495
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001496size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1497 const InstructionSetFeatures* instruction_set_features,
1498 uint32_t num_dex_files,
1499 SafeMap<std::string, std::string>* key_value_store) {
1500 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1501 oat_header_.reset(OatHeader::Create(instruction_set,
1502 instruction_set_features,
1503 num_dex_files,
1504 key_value_store));
1505 size_oat_header_ += sizeof(OatHeader);
1506 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001507 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001508}
1509
1510size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001511 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1512 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001513 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001514 oat_dex_file.offset_ = offset;
1515 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001516 }
1517 return offset;
1518}
1519
Brian Carlstrom389efb02012-01-11 12:06:26 -08001520size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001521 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001522 InitOatClassesMethodVisitor visitor(this, offset);
1523 bool success = VisitDexMethods(&visitor);
1524 CHECK(success);
1525 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001526
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001527 // Update oat_dex_files_.
1528 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001529 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1530 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001531 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001532 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001533 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001534 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001535 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001536 CHECK(oat_class_it == oat_classes_.end());
1537
1538 return offset;
1539}
1540
1541size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001542 InitMapMethodVisitor visitor(this, offset);
1543 bool success = VisitDexMethods(&visitor);
1544 DCHECK(success);
1545 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001546
Brian Carlstrome24fa612011-09-29 00:53:55 -07001547 return offset;
1548}
1549
1550size_t OatWriter::InitOatCode(size_t offset) {
1551 // calculate the offsets within OatHeader to executable code
1552 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001553 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001554 // required to be on a new page boundary
1555 offset = RoundUp(offset, kPageSize);
1556 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001557 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001558 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001559 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001560
Ian Rogers848871b2013-08-05 10:56:33 -07001561 #define DO_TRAMPOLINE(field, fn_name) \
1562 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001563 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1564 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001565 (field) = compiler_driver_->Create ## fn_name(); \
1566 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001567
Ian Rogers848871b2013-08-05 10:56:33 -07001568 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001569 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001570 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001571 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1572 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001573
Ian Rogers848871b2013-08-05 10:56:33 -07001574 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001575 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001576 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1577 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1578 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001579 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001580 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001581 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001582 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001583 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001584 return offset;
1585}
1586
1587size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001588 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1589 bool success = VisitDexMethods(&code_visitor);
1590 DCHECK(success);
1591 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001592
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001593 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001594 InitImageMethodVisitor image_visitor(this, offset);
1595 success = VisitDexMethods(&image_visitor);
1596 DCHECK(success);
1597 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001598 }
Logan Chien8b977d32012-02-21 19:14:55 +08001599
Brian Carlstrome24fa612011-09-29 00:53:55 -07001600 return offset;
1601}
1602
Vladimir Markoaad75c62016-10-03 08:46:48 +00001603void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1604 DCHECK(!HasBootImage());
1605
1606 // Allocate space for app dex cache arrays in the .bss section.
1607 bss_start_ = RoundUp(oat_size_, kPageSize);
1608 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1609 bss_size_ = 0u;
1610 for (const DexFile* dex_file : *dex_files_) {
1611 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1612 DexCacheArraysLayout layout(pointer_size, dex_file);
1613 bss_size_ += layout.Size();
1614 }
1615
1616 bss_roots_offset_ = bss_size_;
1617
1618 // Prepare offsets for .bss String entries.
1619 for (auto& entry : bss_string_entries_) {
1620 DCHECK_EQ(entry.second, 0u);
1621 entry.second = bss_start_ + bss_size_;
1622 bss_size_ += sizeof(GcRoot<mirror::String>);
1623 }
1624}
1625
David Srbeckybc90fd02015-04-22 19:40:27 +01001626bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001627 CHECK(write_state_ == WriteState::kWriteRoData);
1628
Vladimir Markoe079e212016-05-25 12:49:49 +01001629 // Wrap out to update checksum with each write.
1630 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1631 out = &checksum_updating_out;
1632
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001633 if (!WriteClassOffsets(out)) {
1634 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001635 return false;
1636 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001637
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001638 if (!WriteClasses(out)) {
1639 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001640 return false;
1641 }
1642
Vladimir Markof4da6752014-08-01 19:04:18 +01001643 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001644 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001645 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001646 return false;
1647 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001648 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001649 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001650 relative_offset = WriteMaps(out, file_offset, relative_offset);
1651 if (relative_offset == 0) {
1652 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1653 return false;
1654 }
1655
David Srbeckybc90fd02015-04-22 19:40:27 +01001656 // Write padding.
1657 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1658 relative_offset += size_executable_offset_alignment_;
1659 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1660 size_t expected_file_offset = file_offset + relative_offset;
1661 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1662 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1663 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1664 return 0;
1665 }
1666 DCHECK_OFFSET();
1667
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001668 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001669 return true;
1670}
1671
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001672class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1673 public:
1674 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1675 : DexMethodVisitor(writer, offset),
1676 out_(out),
1677 written_bytes_(0u) {}
1678
1679 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1680 const ClassDataItemIterator& it) {
1681 if (it.GetMethodCodeItem() == nullptr) {
1682 // No CodeItem. Native or abstract method.
1683 return true;
1684 }
1685
1686 uint32_t method_idx = it.GetMemberIndex();
1687 CompiledMethod* compiled_method =
1688 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1689
1690 uint32_t length = 0;
1691 const uint8_t* data = nullptr;
1692 // VMap only contains quickening info if this method is not compiled.
1693 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1694 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1695 data = map.data();
1696 length = map.size() * sizeof(map.front());
1697 }
1698
1699 if (!out_->WriteFully(&length, sizeof(length)) ||
1700 !out_->WriteFully(data, length)) {
1701 PLOG(ERROR) << "Failed to write quickening info for "
1702 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1703 return false;
1704 }
1705 offset_ += sizeof(length) + length;
1706 written_bytes_ += sizeof(length) + length;
1707 return true;
1708 }
1709
1710 size_t GetNumberOfWrittenBytes() const {
1711 return written_bytes_;
1712 }
1713
1714 private:
1715 OutputStream* const out_;
1716 size_t written_bytes_;
1717};
1718
1719bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1720 if (!kIsVdexEnabled) {
1721 return true;
1722 }
1723
1724 size_t initial_offset = vdex_size_;
1725 size_t start_offset = RoundUp(initial_offset, 4u);
1726
1727 vdex_size_ = start_offset;
1728 vdex_quickening_info_offset_ = vdex_size_;
1729 size_quickening_info_alignment_ = start_offset - initial_offset;
1730
1731 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1732 if (actual_offset != static_cast<off_t>(start_offset)) {
1733 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1734 << " Expected: " << start_offset
1735 << " Output: " << vdex_out->GetLocation();
1736 return false;
1737 }
1738
1739 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1740 if (!VisitDexMethods(&visitor)) {
1741 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1742 return false;
1743 }
1744
1745 if (!vdex_out->Flush()) {
1746 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1747 << " File: " << vdex_out->GetLocation();
1748 return false;
1749 }
1750
1751 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1752 vdex_size_ += size_quickening_info_;
1753 return true;
1754}
1755
David Brazdil5d5a36b2016-09-14 15:34:10 +01001756bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1757 if (!kIsVdexEnabled) {
1758 return true;
1759 }
1760
1761 if (verifier_deps == nullptr) {
1762 // Nothing to write. Record the offset, but no need
1763 // for alignment.
1764 vdex_verifier_deps_offset_ = vdex_size_;
1765 return true;
1766 }
1767
1768 size_t initial_offset = vdex_size_;
1769 size_t start_offset = RoundUp(initial_offset, 4u);
1770
1771 vdex_size_ = start_offset;
1772 vdex_verifier_deps_offset_ = vdex_size_;
1773 size_verifier_deps_alignment_ = start_offset - initial_offset;
1774
1775 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1776 if (actual_offset != static_cast<off_t>(start_offset)) {
1777 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1778 << " Expected: " << start_offset
1779 << " Output: " << vdex_out->GetLocation();
1780 return false;
1781 }
1782
1783 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001784 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001785
1786 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1787 PLOG(ERROR) << "Failed to write verifier deps."
1788 << " File: " << vdex_out->GetLocation();
1789 return false;
1790 }
1791 if (!vdex_out->Flush()) {
1792 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1793 << " File: " << vdex_out->GetLocation();
1794 return false;
1795 }
1796
1797 size_verifier_deps_ = buffer.size();
1798 vdex_size_ += size_verifier_deps_;
1799 return true;
1800}
1801
David Srbeckybc90fd02015-04-22 19:40:27 +01001802bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001803 CHECK(write_state_ == WriteState::kWriteText);
1804
Vladimir Markoe079e212016-05-25 12:49:49 +01001805 // Wrap out to update checksum with each write.
1806 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1807 out = &checksum_updating_out;
1808
Vladimir Marko944da602016-02-19 12:27:55 +00001809 SetMultiOatRelativePatcherAdjustment();
1810
David Srbeckybc90fd02015-04-22 19:40:27 +01001811 const size_t file_offset = oat_data_offset_;
1812 size_t relative_offset = oat_header_->GetExecutableOffset();
1813 DCHECK_OFFSET();
1814
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001815 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001816 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001817 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001818 return false;
1819 }
1820
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001821 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1822 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001823 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001824 return false;
1825 }
1826
Vladimir Markof4da6752014-08-01 19:04:18 +01001827 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001828 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001829 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1830 return false;
1831 }
1832
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001833 if (kIsDebugBuild) {
1834 uint32_t size_total = 0;
1835 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001836 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1837 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001838
David Brazdil7b49e6c2016-09-01 11:06:18 +01001839 DO_STAT(size_vdex_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001840 DO_STAT(size_dex_file_alignment_);
1841 DO_STAT(size_executable_offset_alignment_);
1842 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001843 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001844 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001845 DO_STAT(size_verifier_deps_);
1846 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001847 DO_STAT(size_quickening_info_);
1848 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001849 DO_STAT(size_interpreter_to_interpreter_bridge_);
1850 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1851 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001852 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001853 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001854 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001855 DO_STAT(size_quick_to_interpreter_bridge_);
1856 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001857 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001858 DO_STAT(size_code_);
1859 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001860 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001861 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001862 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001863 DO_STAT(size_oat_dex_file_location_size_);
1864 DO_STAT(size_oat_dex_file_location_data_);
1865 DO_STAT(size_oat_dex_file_location_checksum_);
1866 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001867 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001868 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001869 DO_STAT(size_oat_lookup_table_alignment_);
1870 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001871 DO_STAT(size_oat_class_offsets_alignment_);
1872 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001873 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001874 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001875 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001876 DO_STAT(size_oat_class_method_offsets_);
1877 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001878
David Brazdil7b49e6c2016-09-01 11:06:18 +01001879 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1880
1881 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1882 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001883 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001884
David Brazdil7b49e6c2016-09-01 11:06:18 +01001885 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1886 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001887
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001888 write_state_ = WriteState::kWriteHeader;
1889 return true;
1890}
1891
1892bool OatWriter::WriteHeader(OutputStream* out,
1893 uint32_t image_file_location_oat_checksum,
1894 uintptr_t image_file_location_oat_begin,
1895 int32_t image_patch_delta) {
1896 CHECK(write_state_ == WriteState::kWriteHeader);
1897
1898 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1899 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001900 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001901 CHECK_EQ(image_patch_delta, 0);
1902 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1903 } else {
1904 CHECK_ALIGNED(image_patch_delta, kPageSize);
1905 oat_header_->SetImagePatchDelta(image_patch_delta);
1906 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001907 oat_header_->UpdateChecksumWithHeaderData();
1908
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001909 const size_t file_offset = oat_data_offset_;
1910
1911 off_t current_offset = out->Seek(0, kSeekCurrent);
1912 if (current_offset == static_cast<off_t>(-1)) {
1913 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1914 return false;
1915 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001916 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001917 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1918 return false;
1919 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001920 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001921
1922 // Flush all other data before writing the header.
1923 if (!out->Flush()) {
1924 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1925 return false;
1926 }
1927 // Write the header.
1928 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001929 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001930 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1931 return false;
1932 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001933 // Flush the header data.
1934 if (!out->Flush()) {
1935 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001936 return false;
1937 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001938
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001939 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1940 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1941 return false;
1942 }
1943 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1944
1945 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001946 return true;
1947}
1948
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001949bool OatWriter::WriteClassOffsets(OutputStream* out) {
1950 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1951 if (oat_dex_file.class_offsets_offset_ != 0u) {
1952 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1953 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1954 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1955 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1956 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001957 return false;
1958 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001959 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1960 return false;
1961 }
1962 }
1963 }
1964 return true;
1965}
1966
1967bool OatWriter::WriteClasses(OutputStream* out) {
1968 for (OatClass& oat_class : oat_classes_) {
1969 if (!oat_class.Write(this, out, oat_data_offset_)) {
1970 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1971 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001972 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001973 }
1974 return true;
1975}
1976
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001977size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001978 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001979 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1980 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1981 return 0;
1982 }
1983 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001984 size_vmap_table_ = relative_offset - vmap_tables_offset;
1985
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001986 return relative_offset;
1987}
1988
1989size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001990 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001991 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001992
Ian Rogers848871b2013-08-05 10:56:33 -07001993 #define DO_TRAMPOLINE(field) \
1994 do { \
1995 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1996 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001997 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001998 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001999 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002000 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002001 return false; \
2002 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002003 size_ ## field += (field)->size(); \
2004 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002005 DCHECK_OFFSET(); \
2006 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002007
Ian Rogers848871b2013-08-05 10:56:33 -07002008 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002009 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002010 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002011 DO_TRAMPOLINE(quick_resolution_trampoline_);
2012 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2013 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002014 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002015 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002016}
2017
Ian Rogers3d504072014-03-01 09:16:49 -08002018size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002019 const size_t file_offset,
2020 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002021 #define VISIT(VisitorType) \
2022 do { \
2023 VisitorType visitor(this, out, file_offset, relative_offset); \
2024 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2025 return 0; \
2026 } \
2027 relative_offset = visitor.GetOffset(); \
2028 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002029
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002030 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002031
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002032 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002033
Vladimir Markob163bb72015-03-31 21:49:49 +01002034 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2035 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2036 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2037
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002038 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002039}
2040
Vladimir Marko944da602016-02-19 12:27:55 +00002041bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002042 // Get the elf file offset of the oat file.
2043 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2044 if (raw_file_offset == static_cast<off_t>(-1)) {
2045 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2046 return false;
2047 }
2048 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2049 return true;
2050}
2051
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002052bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2053 // Read the dex file header and perform minimal verification.
2054 uint8_t raw_header[sizeof(DexFile::Header)];
2055 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2056 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2057 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2058 return false;
2059 }
2060 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2061 return false;
2062 }
2063
2064 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2065 oat_dex_file->dex_file_size_ = header->file_size_;
2066 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2067 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2068 return true;
2069}
2070
2071bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2072 if (!DexFile::IsMagicValid(raw_header)) {
2073 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2074 return false;
2075 }
2076 if (!DexFile::IsVersionValid(raw_header)) {
2077 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2078 return false;
2079 }
2080 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2081 if (header->file_size_ < sizeof(DexFile::Header)) {
2082 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2083 << " File: " << location;
2084 return false;
2085 }
2086 return true;
2087}
2088
David Brazdil7b49e6c2016-09-01 11:06:18 +01002089bool OatWriter::WriteDexFiles(OutputStream* out, File* file) {
2090 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002091
David Brazdil7b49e6c2016-09-01 11:06:18 +01002092 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002093
2094 // Write dex files.
2095 for (OatDexFile& oat_dex_file : oat_dex_files_) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002096 if (!WriteDexFile(out, file, &oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002097 return false;
2098 }
2099 }
2100
2101 // Close sources.
2102 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2103 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2104 }
2105 zipped_dex_files_.clear();
2106 zip_archives_.clear();
2107 raw_dex_files_.clear();
2108 return true;
2109}
2110
David Brazdil7b49e6c2016-09-01 11:06:18 +01002111bool OatWriter::WriteDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2112 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002113 return false;
2114 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002115 if (profile_compilation_info_ != nullptr) {
2116 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2117 return false;
2118 }
2119 } else if (oat_dex_file->source_.IsZipEntry()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002120 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002121 return false;
2122 }
2123 } else if (oat_dex_file->source_.IsRawFile()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002124 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002125 return false;
2126 }
2127 } else {
2128 DCHECK(oat_dex_file->source_.IsRawData());
David Brazdil7b49e6c2016-09-01 11:06:18 +01002129 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002130 return false;
2131 }
2132 }
2133
2134 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002135 if (kIsVdexEnabled) {
2136 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2137 vdex_size_ += oat_dex_file->dex_file_size_;
2138 } else {
2139 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2140 oat_size_ += oat_dex_file->dex_file_size_;
2141 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002142 size_dex_file_ += oat_dex_file->dex_file_size_;
2143 return true;
2144}
2145
2146bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2147 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002148 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2149 size_t start_offset = RoundUp(initial_offset, 4);
2150 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2151 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002152
2153 // Seek to the start of the dex file and flush any pending operations in the stream.
2154 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002155 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2156 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002157 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002158 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002159 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2160 return false;
2161 }
2162 if (!out->Flush()) {
2163 PLOG(ERROR) << "Failed to flush before writing dex file."
2164 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2165 return false;
2166 }
2167 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002168 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002169 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002170 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002171 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2172 return false;
2173 }
2174
David Brazdil7b49e6c2016-09-01 11:06:18 +01002175 if (kIsVdexEnabled) {
2176 vdex_size_ = start_offset;
2177 } else {
2178 oat_size_ = start_offset;
2179 }
2180 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002181 return true;
2182}
2183
Jeff Hao608f2ce2016-10-19 11:17:11 -07002184bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2185 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2186 std::string error_msg;
2187 std::string location(oat_dex_file->GetLocation());
2188 std::unique_ptr<const DexFile> dex_file;
2189 if (oat_dex_file->source_.IsZipEntry()) {
2190 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2191 std::unique_ptr<MemMap> mem_map(
2192 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2193 dex_file = DexFile::Open(location,
2194 zip_entry->GetCrc32(),
2195 std::move(mem_map),
2196 /* verify */ true,
2197 /* verify_checksum */ true,
2198 &error_msg);
2199 } else {
2200 DCHECK(oat_dex_file->source_.IsRawFile());
2201 File* raw_file = oat_dex_file->source_.GetRawFile();
2202 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2203 }
2204 Options options;
2205 options.output_to_memmap_ = true;
2206 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2207 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2208 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
2209 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin())) {
2210 return false;
2211 }
2212 // Set the checksum of the new oat dex file to be the original file's checksum.
2213 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2214 return true;
2215}
2216
David Brazdil7b49e6c2016-09-01 11:06:18 +01002217bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002218 File* file,
2219 OatDexFile* oat_dex_file,
2220 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002221 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2222 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002223
2224 // Extract the dex file and get the extracted size.
2225 std::string error_msg;
2226 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2227 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2228 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2229 return false;
2230 }
2231 if (file->Flush() != 0) {
2232 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2233 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2234 return false;
2235 }
2236 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2237 if (extracted_end == static_cast<off_t>(-1)) {
2238 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2239 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2240 return false;
2241 }
2242 if (extracted_end < static_cast<off_t>(start_offset)) {
2243 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2244 << " Start: " << start_offset
2245 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2246 return false;
2247 }
2248 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2249 if (extracted_size < sizeof(DexFile::Header)) {
2250 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2251 << extracted_size << " File: " << oat_dex_file->GetLocation();
2252 return false;
2253 }
2254
2255 // Read the dex file header and extract required data to OatDexFile.
2256 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2257 if (actual_offset != static_cast<off_t>(start_offset)) {
2258 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2259 << " Expected: " << start_offset
2260 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2261 return false;
2262 }
2263 if (!ReadDexFileHeader(file, oat_dex_file)) {
2264 return false;
2265 }
2266 if (extracted_size < oat_dex_file->dex_file_size_) {
2267 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2268 << " file size from header: " << oat_dex_file->dex_file_size_
2269 << " File: " << oat_dex_file->GetLocation();
2270 return false;
2271 }
2272
2273 // Override the checksum from header with the CRC from ZIP entry.
2274 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2275
2276 // Seek both file and stream to the end offset.
2277 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2278 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2279 if (actual_offset != static_cast<off_t>(end_offset)) {
2280 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2281 << " Expected: " << end_offset
2282 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2283 return false;
2284 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002285 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002286 if (actual_offset != static_cast<off_t>(end_offset)) {
2287 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2288 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2289 return false;
2290 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002291 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002292 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2293 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2294 return false;
2295 }
2296
2297 // If we extracted more than the size specified in the header, truncate the file.
2298 if (extracted_size > oat_dex_file->dex_file_size_) {
2299 if (file->SetLength(end_offset) != 0) {
2300 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002301 << " File: " << oat_dex_file->GetLocation()
2302 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002303 return false;
2304 }
2305 }
2306
2307 return true;
2308}
2309
David Brazdil7b49e6c2016-09-01 11:06:18 +01002310bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002311 File* file,
2312 OatDexFile* oat_dex_file,
2313 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002314 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2315 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002316
2317 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2318 if (input_offset != static_cast<off_t>(0)) {
2319 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2320 << " Expected: 0"
2321 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2322 return false;
2323 }
2324 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2325 return false;
2326 }
2327
2328 // Copy the input dex file using sendfile().
2329 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2330 PLOG(ERROR) << "Failed to copy dex file to oat file."
2331 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2332 return false;
2333 }
2334 if (file->Flush() != 0) {
2335 PLOG(ERROR) << "Failed to flush dex file."
2336 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2337 return false;
2338 }
2339
2340 // Check file position and seek the stream to the end offset.
2341 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2342 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2343 if (actual_offset != static_cast<off_t>(end_offset)) {
2344 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2345 << " Expected: " << end_offset
2346 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2347 return false;
2348 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002349 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002350 if (actual_offset != static_cast<off_t>(end_offset)) {
2351 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2352 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2353 return false;
2354 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002355 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002356 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2357 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2358 return false;
2359 }
2360
2361 return true;
2362}
2363
David Brazdil7b49e6c2016-09-01 11:06:18 +01002364bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002365 OatDexFile* oat_dex_file,
2366 const uint8_t* dex_file) {
2367 // Note: The raw data has already been checked to contain the header
2368 // and all the data that the header specifies as the file size.
2369 DCHECK(dex_file != nullptr);
2370 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2371 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2372
David Brazdil7b49e6c2016-09-01 11:06:18 +01002373 if (!out->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002374 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002375 << " to " << out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002376 return false;
2377 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002378 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002379 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2380 << " File: " << oat_dex_file->GetLocation();
2381 return false;
2382 }
2383
2384 // Update dex file size and resize class offsets in the OatDexFile.
2385 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2386 oat_dex_file->dex_file_size_ = header->file_size_;
2387 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2388 return true;
2389}
2390
2391bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2392 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2393
David Brazdil181e1cc2016-09-01 16:38:47 +00002394 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2395 if (initial_offset == static_cast<off_t>(-1)) {
2396 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2397 return false;
2398 }
2399
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002400 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2401 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2402 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2403 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2404 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2405 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2406 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2407 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2408 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2409 return false;
2410 }
2411
2412 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2413 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2414
2415 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2416 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2417
2418 // Write OatDexFile.
2419 if (!oat_dex_file->Write(this, rodata)) {
2420 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2421 return false;
2422 }
2423 }
2424
David Brazdil181e1cc2016-09-01 16:38:47 +00002425 // Seek back to the initial position.
2426 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2427 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2428 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2429 return false;
2430 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002431
David Brazdilb92ba622016-09-01 16:00:30 +00002432 return true;
2433}
2434
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002435bool OatWriter::OpenDexFiles(
2436 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002437 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002438 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2439 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2440 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2441
2442 if (oat_dex_files_.empty()) {
2443 // Nothing to do.
2444 return true;
2445 }
2446
2447 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002448 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2449
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002450 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002451 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2452 length,
2453 PROT_READ | PROT_WRITE,
2454 MAP_SHARED,
2455 file->Fd(),
2456 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2457 /* low_4gb */ false,
2458 file->GetPath().c_str(),
2459 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002460 if (dex_files_map == nullptr) {
2461 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2462 << " error: " << error_msg;
2463 return false;
2464 }
2465 std::vector<std::unique_ptr<const DexFile>> dex_files;
2466 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2467 // Make sure no one messed with input files while we were copying data.
2468 // At the very least we need consistent file size and number of class definitions.
2469 const uint8_t* raw_dex_file =
2470 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2471 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2472 // Note: ValidateDexFileHeader() already logged an error message.
2473 LOG(ERROR) << "Failed to verify written dex file header!"
2474 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2475 << " ~ " << static_cast<const void*>(raw_dex_file);
2476 return false;
2477 }
2478 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2479 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2480 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2481 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2482 << " Output: " << file->GetPath();
2483 return false;
2484 }
2485 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2486 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2487 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2488 << " Output: " << file->GetPath();
2489 return false;
2490 }
2491
2492 // Now, open the dex file.
2493 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2494 oat_dex_file.dex_file_size_,
2495 oat_dex_file.GetLocation(),
2496 oat_dex_file.dex_file_location_checksum_,
2497 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002498 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002499 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002500 &error_msg));
2501 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002502 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2503 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002504 return false;
2505 }
2506 }
2507
2508 *opened_dex_files_map = std::move(dex_files_map);
2509 *opened_dex_files = std::move(dex_files);
2510 return true;
2511}
2512
2513bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002514 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002515 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2516 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2517
David Brazdil7b49e6c2016-09-01 11:06:18 +01002518 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2519 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2520 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2521 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2522 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2523 return false;
2524 }
2525
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002526 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2527 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2528 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002529 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2530
2531 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2532 oat_dex_file->class_offsets_.empty()) {
2533 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002534 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002535
2536 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2537 if (table_size == 0u) {
2538 continue;
2539 }
2540
2541 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002542 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002543 const DexFile& dex_file = *opened_dex_files[i];
2544 {
2545 std::unique_ptr<TypeLookupTable> type_lookup_table =
2546 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2547 type_lookup_table_oat_dex_files_.push_back(
2548 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2549 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2550 }
2551 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002552
2553 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002554 size_t initial_offset = oat_size_;
2555 size_t rodata_offset = RoundUp(initial_offset, 4);
2556 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002557
2558 if (padding_size != 0u) {
2559 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002560 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002561 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2562 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002563 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002564 return false;
2565 }
2566 }
2567
2568 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002569 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002570 DCHECK_EQ(table_size, table->RawDataLength());
2571
David Brazdil7b49e6c2016-09-01 11:06:18 +01002572 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002573 PLOG(ERROR) << "Failed to write lookup table."
2574 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002575 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002576 return false;
2577 }
2578
2579 oat_dex_file->lookup_table_offset_ = rodata_offset;
2580
David Brazdil7b49e6c2016-09-01 11:06:18 +01002581 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002582 size_oat_lookup_table_ += table_size;
2583 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002584 }
2585
David Brazdil7b49e6c2016-09-01 11:06:18 +01002586 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002587 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002588 << " File: " << oat_rodata->GetLocation();
2589 return false;
2590 }
2591
2592 return true;
2593}
2594
2595bool OatWriter::WriteVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002596 if (!kIsVdexEnabled) {
2597 return true;
2598 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002599 off_t actual_offset = vdex_out->Seek(0, kSeekSet);
2600 if (actual_offset != 0) {
2601 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2602 << " File: " << vdex_out->GetLocation();
2603 return false;
2604 }
2605
David Brazdil5d5a36b2016-09-14 15:34:10 +01002606 DCHECK_NE(vdex_dex_files_offset_, 0u);
2607 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2608
2609 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002610 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2611 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002612
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002613 VdexFile::Header vdex_header(
2614 dex_section_size, verifier_deps_section_size, quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002615 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2616 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002617 return false;
2618 }
2619
David Brazdil5d5a36b2016-09-14 15:34:10 +01002620 if (!vdex_out->Flush()) {
2621 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2622 << " File: " << vdex_out->GetLocation();
2623 return false;
2624 }
2625
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002626 return true;
2627}
2628
Vladimir Markof4da6752014-08-01 19:04:18 +01002629bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2630 static const uint8_t kPadding[] = {
2631 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2632 };
2633 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002634 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002635 return false;
2636 }
2637 size_code_alignment_ += aligned_code_delta;
2638 return true;
2639}
2640
Vladimir Marko944da602016-02-19 12:27:55 +00002641void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2642 DCHECK(dex_files_ != nullptr);
2643 DCHECK(relative_patcher_ != nullptr);
2644 DCHECK_NE(oat_data_offset_, 0u);
2645 if (image_writer_ != nullptr && !dex_files_->empty()) {
2646 // The oat data begin may not be initialized yet but the oat file offset is ready.
2647 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2648 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2649 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002650 }
2651}
2652
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002653OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2654 DexFileSource source,
2655 CreateTypeLookupTable create_type_lookup_table)
2656 : source_(source),
2657 create_type_lookup_table_(create_type_lookup_table),
2658 dex_file_size_(0),
2659 offset_(0),
2660 dex_file_location_size_(strlen(dex_file_location)),
2661 dex_file_location_data_(dex_file_location),
2662 dex_file_location_checksum_(0u),
2663 dex_file_offset_(0u),
2664 class_offsets_offset_(0u),
2665 lookup_table_offset_(0u),
2666 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002667}
2668
2669size_t OatWriter::OatDexFile::SizeOf() const {
2670 return sizeof(dex_file_location_size_)
2671 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002672 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002673 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002674 + sizeof(class_offsets_offset_)
2675 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002676}
2677
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002678void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2679 DCHECK_EQ(class_offsets_offset_, 0u);
2680 if (!class_offsets_.empty()) {
2681 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002682 size_t initial_offset = oat_writer->oat_size_;
2683 size_t offset = RoundUp(initial_offset, 4);
2684 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002685 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002686 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002687 }
2688}
2689
2690bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2691 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002692 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002693
Vladimir Markoe079e212016-05-25 12:49:49 +01002694 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002695 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002696 return false;
2697 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002698 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002699
Vladimir Markoe079e212016-05-25 12:49:49 +01002700 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002701 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002702 return false;
2703 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002704 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002705
Vladimir Markoe079e212016-05-25 12:49:49 +01002706 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002707 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002708 return false;
2709 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002710 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002711
Vladimir Markoe079e212016-05-25 12:49:49 +01002712 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002713 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002714 return false;
2715 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002716 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002717
Vladimir Markoe079e212016-05-25 12:49:49 +01002718 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002719 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2720 return false;
2721 }
2722 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2723
Vladimir Markoe079e212016-05-25 12:49:49 +01002724 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002725 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2726 return false;
2727 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002728 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002729
2730 return true;
2731}
2732
2733bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002734 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002735 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2736 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002737 return false;
2738 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002739 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002740 return true;
2741}
2742
Brian Carlstromba150c32013-08-27 17:31:03 -07002743OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002744 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002745 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002746 mirror::Class::Status status)
2747 : compiled_methods_(compiled_methods) {
2748 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002749 CHECK_LE(num_non_null_compiled_methods, num_methods);
2750
Brian Carlstrom265091e2013-01-30 14:08:26 -08002751 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002752 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2753
2754 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2755 // apply when there are 0 methods, we just arbitrarily say that 0
2756 // methods means kOatClassNoneCompiled and that we won't use
2757 // kOatClassAllCompiled unless there is at least one compiled
2758 // method. This means in an interpretter only system, we can assert
2759 // that all classes are kOatClassNoneCompiled.
2760 if (num_non_null_compiled_methods == 0) {
2761 type_ = kOatClassNoneCompiled;
2762 } else if (num_non_null_compiled_methods == num_methods) {
2763 type_ = kOatClassAllCompiled;
2764 } else {
2765 type_ = kOatClassSomeCompiled;
2766 }
2767
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002768 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002769 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002770 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002771
2772 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2773 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002774 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002775 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2776 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2777 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2778 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002779 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002780 method_bitmap_size_ = 0;
2781 }
2782
2783 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002784 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002785 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002786 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2787 } else {
2788 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2789 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2790 if (type_ == kOatClassSomeCompiled) {
2791 method_bitmap_->SetBit(i);
2792 }
2793 }
2794 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002795}
2796
Brian Carlstrom265091e2013-01-30 14:08:26 -08002797size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2798 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002799 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2800 if (method_offset == 0) {
2801 return 0;
2802 }
2803 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002804}
2805
2806size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2807 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002808 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002809}
2810
2811size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002812 return sizeof(status_)
2813 + sizeof(type_)
2814 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2815 + method_bitmap_size_
2816 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002817}
2818
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002819bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002820 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002821 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002822 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002823 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002824 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002825 return false;
2826 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002827 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002828
Vladimir Markoe079e212016-05-25 12:49:49 +01002829 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002830 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002831 return false;
2832 }
2833 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002834
Brian Carlstromba150c32013-08-27 17:31:03 -07002835 if (method_bitmap_size_ != 0) {
2836 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002837 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002838 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002839 return false;
2840 }
2841 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002842
Vladimir Markoe079e212016-05-25 12:49:49 +01002843 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002844 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002845 return false;
2846 }
2847 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2848 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002849
Vladimir Markoe079e212016-05-25 12:49:49 +01002850 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002851 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002852 return false;
2853 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002854 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002855 return true;
2856}
2857
Brian Carlstrome24fa612011-09-29 00:53:55 -07002858} // namespace art