blob: 6de08c837eb5d778eed5ff11803c4c9f53304c12 [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),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000303 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700304 size_dex_file_alignment_(0),
305 size_executable_offset_alignment_(0),
306 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700307 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700308 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100309 size_verifier_deps_(0),
310 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100311 size_quickening_info_(0),
312 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700313 size_interpreter_to_interpreter_bridge_(0),
314 size_interpreter_to_compiled_code_bridge_(0),
315 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800316 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700317 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700318 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700319 size_quick_to_interpreter_bridge_(0),
320 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100321 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700322 size_code_(0),
323 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100324 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100325 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700326 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700327 size_oat_dex_file_location_size_(0),
328 size_oat_dex_file_location_data_(0),
329 size_oat_dex_file_location_checksum_(0),
330 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000331 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000332 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000333 size_oat_lookup_table_alignment_(0),
334 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000335 size_oat_class_offsets_alignment_(0),
336 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700337 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700338 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700339 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100340 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000341 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700342 absolute_patch_locations_(),
343 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000344}
345
346bool OatWriter::AddDexFileSource(const char* filename,
347 const char* location,
348 CreateTypeLookupTable create_type_lookup_table) {
349 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
350 uint32_t magic;
351 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700352 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
353 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000354 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
355 return false;
356 } else if (IsDexMagic(magic)) {
357 // The file is open for reading, not writing, so it's OK to let the File destructor
358 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700359 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000360 oat_dex_files_.emplace_back(location,
361 DexFileSource(raw_dex_files_.back().get()),
362 create_type_lookup_table);
363 } else if (IsZipMagic(magic)) {
364 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
365 return false;
366 }
367 } else {
368 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
369 return false;
370 }
371 return true;
372}
373
374// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700375bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000376 const char* location,
377 CreateTypeLookupTable create_type_lookup_table) {
378 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
379 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700380 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000381 ZipArchive* zip_archive = zip_archives_.back().get();
382 if (zip_archive == nullptr) {
383 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
384 << error_msg;
385 return false;
386 }
387 for (size_t i = 0; ; ++i) {
388 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
389 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
390 if (entry == nullptr) {
391 break;
392 }
393 zipped_dex_files_.push_back(std::move(entry));
394 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
395 const char* full_location = zipped_dex_file_locations_.back().c_str();
396 oat_dex_files_.emplace_back(full_location,
397 DexFileSource(zipped_dex_files_.back().get()),
398 create_type_lookup_table);
399 }
400 if (zipped_dex_file_locations_.empty()) {
401 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
402 return false;
403 }
404 return true;
405}
406
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000407// Add dex file source(s) from a vdex file specified by a file handle.
408bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
409 const char* location,
410 CreateTypeLookupTable create_type_lookup_table) {
411 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
412 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000413 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000414 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
415 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000416 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
417 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000418 }
419 if (!DexFile::IsMagicValid(current_dex_data)) {
420 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
421 return false;
422 }
423 // We used `zipped_dex_file_locations_` to keep the strings in memory.
424 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
425 const char* full_location = zipped_dex_file_locations_.back().c_str();
426 oat_dex_files_.emplace_back(full_location,
427 DexFileSource(current_dex_data),
428 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000429 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000430 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000431
432 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
433 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
434 return false;
435 }
436
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000437 if (oat_dex_files_.empty()) {
438 LOG(ERROR) << "No dex files in vdex file created from " << location;
439 return false;
440 }
441 return true;
442}
443
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444// Add dex file source from raw memory.
445bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
446 const char* location,
447 uint32_t location_checksum,
448 CreateTypeLookupTable create_type_lookup_table) {
449 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
450 if (data.size() < sizeof(DexFile::Header)) {
451 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
452 << data.size() << " File: " << location;
453 return false;
454 }
455 if (!ValidateDexFileHeader(data.data(), location)) {
456 return false;
457 }
458 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
459 if (data.size() < header->file_size_) {
460 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
461 << " file size from header: " << header->file_size_ << " File: " << location;
462 return false;
463 }
464
465 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
466 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
467 return true;
468}
469
470dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
471 dchecked_vector<const char*> locations;
472 locations.reserve(oat_dex_files_.size());
473 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
474 locations.push_back(oat_dex_file.GetLocation());
475 }
476 return locations;
477}
478
479bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100480 File* vdex_file,
481 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000482 InstructionSet instruction_set,
483 const InstructionSetFeatures* instruction_set_features,
484 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800485 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000486 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000487 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
488 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
489 CHECK(write_state_ == WriteState::kAddingDexFileSources);
490
David Brazdil7b49e6c2016-09-01 11:06:18 +0100491 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
492 if (!RecordOatDataOffset(oat_rodata)) {
493 return false;
494 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495
496 std::unique_ptr<MemMap> dex_files_map;
497 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100498
499 // Initialize VDEX and OAT headers.
500 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000501 // Reserve space for Vdex header and checksums.
502 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100503 }
504 size_t oat_data_offset = InitOatHeader(instruction_set,
505 instruction_set_features,
506 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
507 key_value_store);
508 oat_size_ = InitOatDexFiles(oat_data_offset);
509
510 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
511
512 if (kIsVdexEnabled) {
513 std::unique_ptr<BufferedOutputStream> vdex_out(
514 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100515 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000516 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100517 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
518 return false;
519 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100520 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000521 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100522 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000523 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100524 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
525 return false;
526 }
527
528 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
529 // difficult because we're not using the OutputStream directly.
530 if (!oat_dex_files_.empty()) {
531 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
532 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
533 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000534 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000535
David Brazdil7b49e6c2016-09-01 11:06:18 +0100536 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000537 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
538 return false;
539 }
540
David Brazdil7b49e6c2016-09-01 11:06:18 +0100541 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000542 for (OatDexFile& oat_dex_file : oat_dex_files_) {
543 oat_dex_file.ReserveClassOffsets(this);
544 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100545
David Brazdil7b49e6c2016-09-01 11:06:18 +0100546 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000547 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
548 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000549 }
550
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000551 *opened_dex_files_map = std::move(dex_files_map);
552 *opened_dex_files = std::move(dex_files);
553 write_state_ = WriteState::kPrepareLayout;
554 return true;
555}
556
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100557void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000558 CHECK(write_state_ == WriteState::kPrepareLayout);
559
Vladimir Marko944da602016-02-19 12:27:55 +0000560 relative_patcher_ = relative_patcher;
561 SetMultiOatRelativePatcherAdjustment();
562
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000563 if (compiling_boot_image_) {
564 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800565 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100566 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000567 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100568
David Brazdil7b49e6c2016-09-01 11:06:18 +0100569 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800570 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000571 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800572 offset = InitOatClasses(offset);
573 }
574 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000575 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100576 offset = InitOatMaps(offset);
577 }
578 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000579 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800580 offset = InitOatCode(offset);
581 }
582 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000583 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800584 offset = InitOatCodeDexFiles(offset);
585 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100586 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700587
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800588 if (!HasBootImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000589 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
590 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100591 }
592
Brian Carlstrome24fa612011-09-29 00:53:55 -0700593 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800594 if (compiling_boot_image_) {
595 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000596 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800597 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000598
599 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700600}
601
Ian Rogers0571d352011-11-03 19:51:38 -0700602OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700603}
604
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100605class OatWriter::DexMethodVisitor {
606 public:
607 DexMethodVisitor(OatWriter* writer, size_t offset)
608 : writer_(writer),
609 offset_(offset),
610 dex_file_(nullptr),
611 class_def_index_(DexFile::kDexNoIndex) {
612 }
613
614 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
615 DCHECK(dex_file_ == nullptr);
616 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
617 dex_file_ = dex_file;
618 class_def_index_ = class_def_index;
619 return true;
620 }
621
622 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
623
624 virtual bool EndClass() {
625 if (kIsDebugBuild) {
626 dex_file_ = nullptr;
627 class_def_index_ = DexFile::kDexNoIndex;
628 }
629 return true;
630 }
631
632 size_t GetOffset() const {
633 return offset_;
634 }
635
636 protected:
637 virtual ~DexMethodVisitor() { }
638
639 OatWriter* const writer_;
640
641 // The offset is usually advanced for each visited method by the derived class.
642 size_t offset_;
643
644 // The dex file and class def index are set in StartClass().
645 const DexFile* dex_file_;
646 size_t class_def_index_;
647};
648
649class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
650 public:
651 OatDexMethodVisitor(OatWriter* writer, size_t offset)
652 : DexMethodVisitor(writer, offset),
653 oat_class_index_(0u),
654 method_offsets_index_(0u) {
655 }
656
657 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
658 DexMethodVisitor::StartClass(dex_file, class_def_index);
659 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
660 method_offsets_index_ = 0u;
661 return true;
662 }
663
664 bool EndClass() {
665 ++oat_class_index_;
666 return DexMethodVisitor::EndClass();
667 }
668
669 protected:
670 size_t oat_class_index_;
671 size_t method_offsets_index_;
672};
673
674class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
675 public:
676 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
677 : DexMethodVisitor(writer, offset),
678 compiled_methods_(),
679 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000680 size_t num_classes = 0u;
681 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
682 num_classes += oat_dex_file.class_offsets_.size();
683 }
684 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100685 compiled_methods_.reserve(256u);
686 }
687
688 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
689 DexMethodVisitor::StartClass(dex_file, class_def_index);
690 compiled_methods_.clear();
691 num_non_null_compiled_methods_ = 0u;
692 return true;
693 }
694
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300695 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
696 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100697 // Fill in the compiled_methods_ array for methods that have a
698 // CompiledMethod. We track the number of non-null entries in
699 // num_non_null_compiled_methods_ since we only want to allocate
700 // OatMethodOffsets for the compiled methods.
701 uint32_t method_idx = it.GetMemberIndex();
702 CompiledMethod* compiled_method =
703 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
704 compiled_methods_.push_back(compiled_method);
705 if (compiled_method != nullptr) {
706 ++num_non_null_compiled_methods_;
707 }
708 return true;
709 }
710
711 bool EndClass() {
712 ClassReference class_ref(dex_file_, class_def_index_);
713 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
714 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700715 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100716 status = compiled_class->GetStatus();
717 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
718 status = mirror::Class::kStatusError;
719 } else {
720 status = mirror::Class::kStatusNotReady;
721 }
722
Vladimir Marko49b0f452015-12-10 13:49:19 +0000723 writer_->oat_classes_.emplace_back(offset_,
724 compiled_methods_,
725 num_non_null_compiled_methods_,
726 status);
727 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100728 return DexMethodVisitor::EndClass();
729 }
730
731 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000732 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100733 size_t num_non_null_compiled_methods_;
734};
735
736class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
737 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100738 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100739 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100740 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
741 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100742 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100743 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
744 }
745
746 bool EndClass() {
747 OatDexMethodVisitor::EndClass();
748 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100749 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100750 }
751 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100752 }
753
754 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700755 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000756 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100757 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
758
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100759 if (it.GetMethodCodeItem() != nullptr) {
760 current_quickening_info_offset_ += sizeof(uint32_t);
761 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762 if (compiled_method != nullptr) {
763 // Derived from CompiledMethod.
764 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100765
Vladimir Marko35831e82015-09-11 11:59:18 +0100766 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
767 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800768 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800769
David Srbecky009e2a62015-04-15 02:46:30 +0100770 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100771 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800772 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000773 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000774 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
775 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800776 // Duplicate methods, we want the same code for both of them so that the oat writer puts
777 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800778 } else {
779 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100780 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800781 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000782 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100783 quick_code_offset = dedupe_map_.GetOrCreate(
784 compiled_method,
785 [this, &deduped, compiled_method, &it, thumb_offset]() {
786 deduped = false;
787 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
788 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800789 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100790
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100791 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000792 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100793 // TODO: Should this be a hard failure?
794 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700795 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000796 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
797 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100798 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000799 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100800 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800801 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100802
Elliott Hughes956af0f2014-12-11 14:34:28 -0800803 // Update quick method header.
804 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
805 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700806 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
808 // to 0-offset and we need to adjust it by code_offset.
809 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100810 if (!compiled_method->GetQuickCode().empty()) {
811 // If the code is compiled, we write the offset of the stack map relative
812 // to the code,
813 if (vmap_table_offset != 0u) {
814 vmap_table_offset += code_offset;
815 DCHECK_LT(vmap_table_offset, code_offset);
816 }
817 } else {
818 if (kIsVdexEnabled) {
819 // We write the offset in the .vdex file.
820 DCHECK_EQ(vmap_table_offset, 0u);
821 vmap_table_offset = current_quickening_info_offset_;
822 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
823 current_quickening_info_offset_ += map.size() * sizeof(map.front());
824 } else {
825 // We write the offset of the quickening info relative to the code.
826 vmap_table_offset += code_offset;
827 DCHECK_LT(vmap_table_offset, code_offset);
828 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800829 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800830 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
831 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
832 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100833 *method_header = OatQuickMethodHeader(vmap_table_offset,
834 frame_size_in_bytes,
835 core_spill_mask,
836 fp_spill_mask,
837 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100838
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000839 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800840 // Update offsets. (Checksum is updated when writing.)
841 offset_ += sizeof(*method_header); // Method header is prepended before code.
842 offset_ += code_size;
843 // Record absolute patch locations.
844 if (!compiled_method->GetPatches().empty()) {
845 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
846 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000847 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100848 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100849 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000850 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
851 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
852 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
853 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100854 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100855 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800856 }
Alex Light78382fa2014-06-06 15:45:32 -0700857
David Srbecky91cc06c2016-03-07 16:13:58 +0000858 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000859 // Exclude quickened dex methods (code_size == 0) since they have no native code.
860 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
861 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800862 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000863 debug::MethodDebugInfo info = debug::MethodDebugInfo();
864 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000865 info.dex_file = dex_file_;
866 info.class_def_index = class_def_index_;
867 info.dex_method_index = it.GetMemberIndex();
868 info.access_flags = it.GetMethodAccessFlags();
869 info.code_item = it.GetMethodCodeItem();
870 info.isa = compiled_method->GetInstructionSet();
871 info.deduped = deduped;
872 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
873 info.is_optimized = method_header->IsOptimized();
874 info.is_code_address_text_relative = true;
875 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
876 info.code_size = code_size;
877 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
878 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
879 info.cfi = compiled_method->GetCFIInfo();
880 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100881 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100882
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100883 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
884 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
885 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100886 ++method_offsets_index_;
887 }
888
889 return true;
890 }
891
892 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000893 struct CodeOffsetsKeyComparator {
894 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100895 // Code is deduplicated by CompilerDriver, compare only data pointers.
896 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
897 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000898 }
899 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100900 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
901 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000902 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100903 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
904 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000905 }
906 return false;
907 }
908 };
909
David Srbecky009e2a62015-04-15 02:46:30 +0100910 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
911 const ClassDataItemIterator& it,
912 uint32_t thumb_offset) {
913 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100914 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100915 offset_ += CodeAlignmentSize(offset_, *compiled_method);
916 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100917 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
918 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
919 }
920
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100921 // Deduplication is already done on a pointer basis by the compiler driver,
922 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100923 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100924
David Srbecky009e2a62015-04-15 02:46:30 +0100925 // Cache of compiler's --debuggable option.
926 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100927
928 // Offset in the vdex file for the quickening info.
929 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100930};
931
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100932class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
933 public:
934 InitMapMethodVisitor(OatWriter* writer, size_t offset)
935 : OatDexMethodVisitor(writer, offset) {
936 }
937
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700938 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700939 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000940 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
942
943 if (compiled_method != nullptr) {
944 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100945 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
946 // be in the vdex file.
947 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700948 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100949
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100950 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
951 uint32_t map_size = map.size() * sizeof(map[0]);
952 if (map_size != 0u) {
953 size_t offset = dedupe_map_.GetOrCreate(
954 map.data(),
955 [this, map_size]() {
956 uint32_t new_offset = offset_;
957 offset_ += map_size;
958 return new_offset;
959 });
960 // Code offset is not initialized yet, so set the map offset to 0u-offset.
961 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700962 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100963 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100964 }
965 ++method_offsets_index_;
966 }
967
968 return true;
969 }
970
971 private:
972 // Deduplication is already done on a pointer basis by the compiler driver,
973 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100974 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100975};
976
977class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
978 public:
979 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800980 : OatDexMethodVisitor(writer, offset),
981 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100982 }
983
984 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700985 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800986 const DexFile::TypeId& type_id =
987 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
988 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
989 // Skip methods that are not in the image.
990 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
991 return true;
992 }
993
Vladimir Marko49b0f452015-12-10 13:49:19 +0000994 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100995 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
996
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800997 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100998 if (compiled_method != nullptr) {
999 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1000 offsets = oat_class->method_offsets_[method_offsets_index_];
1001 ++method_offsets_index_;
1002 }
1003
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001004 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001005 // Unchecked as we hold mutator_lock_ on entry.
1006 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001007 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001008 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
1009 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001010 ArtMethod* method;
1011 if (writer_->HasBootImage()) {
1012 const InvokeType invoke_type = it.GetMethodInvokeType(
1013 dex_file_->GetClassDef(class_def_index_));
1014 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1015 *dex_file_,
1016 it.GetMemberIndex(),
1017 dex_cache,
1018 ScopedNullHandle<mirror::ClassLoader>(),
1019 nullptr,
1020 invoke_type);
1021 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001022 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001023 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001024 soa.Self()->AssertPendingException();
1025 mirror::Throwable* exc = soa.Self()->GetException();
1026 std::string dump = exc->Dump();
1027 LOG(FATAL) << dump;
1028 UNREACHABLE();
1029 }
1030 } else {
1031 // Should already have been resolved by the compiler, just peek into the dex cache.
1032 // It may not be resolved if the class failed to verify, in this case, don't set the
1033 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1034 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001035 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001036 if (method != nullptr &&
1037 compiled_method != nullptr &&
1038 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001039 method->SetEntryPointFromQuickCompiledCodePtrSize(
1040 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1041 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001042
1043 return true;
1044 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001045
1046 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001047 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001048};
1049
1050class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1051 public:
1052 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001053 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001054 : OatDexMethodVisitor(writer, relative_offset),
1055 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001056 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001057 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001058 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001059 class_linker_(Runtime::Current()->GetClassLinker()),
1060 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001061 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001062 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001063 // If we're creating the image, the address space must be ready so that we can apply patches.
1064 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001065 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001066 }
1067
Vladimir Markof4da6752014-08-01 19:04:18 +01001068 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001069 }
1070
1071 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001072 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001073 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1074 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001075 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001076 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001077 }
1078 return true;
1079 }
1080
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001081 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001082 bool result = OatDexMethodVisitor::EndClass();
1083 if (oat_class_index_ == writer_->oat_classes_.size()) {
1084 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001085 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001086 if (UNLIKELY(offset_ == 0u)) {
1087 PLOG(ERROR) << "Failed to write final relative call thunks";
1088 result = false;
1089 }
1090 }
1091 return result;
1092 }
1093
1094 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001095 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001096 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001097 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1098
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001099 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001100 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001101 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001102 size_t file_offset = file_offset_;
1103 OutputStream* out = out_;
1104
Vladimir Marko35831e82015-09-11 11:59:18 +01001105 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1106 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001107
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001108 // Deduplicate code arrays.
1109 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1110 if (method_offsets.code_offset_ > offset_) {
1111 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1112 if (offset_ == 0u) {
1113 ReportWriteFailure("relative call thunk", it);
1114 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001115 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001116 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1117 if (alignment_size != 0) {
1118 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001119 ReportWriteFailure("code alignment padding", it);
1120 return false;
1121 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001122 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001123 DCHECK_OFFSET_();
1124 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001125 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001126 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1127 DCHECK_EQ(method_offsets.code_offset_,
1128 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001129 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001130 const OatQuickMethodHeader& method_header =
1131 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001132 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001133 ReportWriteFailure("method header", it);
1134 return false;
1135 }
1136 writer_->size_method_header_ += sizeof(method_header);
1137 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001138 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001139
1140 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001141 patched_code_.assign(quick_code.begin(), quick_code.end());
1142 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001143 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001144 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001145 switch (patch.GetType()) {
1146 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001147 // NOTE: Relative calls across oat files are not supported.
1148 uint32_t target_offset = GetTargetOffset(patch);
1149 writer_->relative_patcher_->PatchCall(&patched_code_,
1150 literal_offset,
1151 offset_ + literal_offset,
1152 target_offset);
1153 break;
1154 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001155 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001156 uint32_t target_offset = GetDexCacheOffset(patch);
1157 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1158 patch,
1159 offset_ + literal_offset,
1160 target_offset);
1161 break;
1162 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001163 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001164 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1165 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1166 patch,
1167 offset_ + literal_offset,
1168 target_offset);
1169 break;
1170 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001171 case LinkerPatch::Type::kStringBssEntry: {
1172 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1173 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1174 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1175 patch,
1176 offset_ + literal_offset,
1177 target_offset);
1178 break;
1179 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001180 case LinkerPatch::Type::kTypeRelative: {
1181 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1182 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1183 patch,
1184 offset_ + literal_offset,
1185 target_offset);
1186 break;
1187 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001188 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001189 uint32_t target_offset = GetTargetOffset(patch);
1190 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1191 break;
1192 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001193 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001194 ArtMethod* method = GetTargetMethod(patch);
1195 PatchMethodAddress(&patched_code_, literal_offset, method);
1196 break;
1197 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001198 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001199 mirror::String* string = GetTargetString(patch);
1200 PatchObjectAddress(&patched_code_, literal_offset, string);
1201 break;
1202 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001203 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001204 mirror::Class* type = GetTargetType(patch);
1205 PatchObjectAddress(&patched_code_, literal_offset, type);
1206 break;
1207 }
1208 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001209 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001210 break;
1211 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001212 }
1213 }
1214 }
1215
Vladimir Markoe079e212016-05-25 12:49:49 +01001216 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001217 ReportWriteFailure("method code", it);
1218 return false;
1219 }
1220 writer_->size_code_ += code_size;
1221 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001222 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001223 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001224 ++method_offsets_index_;
1225 }
1226
1227 return true;
1228 }
1229
1230 private:
1231 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001232 const size_t file_offset_;
1233 const ScopedObjectAccess soa_;
1234 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001235 ClassLinker* const class_linker_;
1236 mirror::DexCache* dex_cache_;
1237 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001238
1239 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1240 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001241 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001242 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001243
Mathieu Chartiere401d142015-04-22 13:56:20 -07001244 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001245 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001246 MethodReference ref = patch.TargetMethod();
1247 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001248 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1249 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001250 ArtMethod* method = dex_cache->GetResolvedMethod(
1251 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001252 CHECK(method != nullptr);
1253 return method;
1254 }
1255
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001256 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001257 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1258 // If there's no new compiled code, either we're compiling an app and the target method
1259 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001260 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001261 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001262 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001263 PointerSize size =
1264 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001265 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1266 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001267 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001268 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1269 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1270 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1271 target_offset = PointerToLowMemUInt32(oat_code_offset);
1272 } else {
1273 target_offset = target->IsNative()
1274 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1275 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1276 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001277 }
1278 return target_offset;
1279 }
1280
Vladimir Marko052164a2016-04-27 13:54:18 +01001281 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001282 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001283 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001284 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001285 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1286 }
1287
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001288 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001289 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001290 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1291 CHECK(type != nullptr);
1292 return type;
1293 }
1294
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001295 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001296 ScopedObjectAccessUnchecked soa(Thread::Current());
1297 StackHandleScope<1> hs(soa.Self());
1298 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1299 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1300 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1301 patch.TargetStringIndex(),
1302 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001303 DCHECK(string != nullptr);
1304 DCHECK(writer_->HasBootImage() ||
1305 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1306 return string;
1307 }
1308
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001309 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001310 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001311 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1312 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1313 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1314 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001315 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001316 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001317 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1318 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001319 }
1320 }
1321
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001322 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001323 DCHECK(writer_->HasBootImage());
1324 object = writer_->image_writer_->GetImageAddress(object);
1325 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1326 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1327 // TODO: Clean up offset types. The target offset must be treated as signed.
1328 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1329 }
1330
Vladimir Markof4da6752014-08-01 19:04:18 +01001331 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001332 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001333 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001334 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001335 } else {
1336 // NOTE: We're using linker patches for app->boot references when the image can
1337 // be relocated and therefore we need to emit .oat_patches. We're not using this
1338 // for app->app references, so check that the object is in the image space.
1339 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001340 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001341 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001342 uint32_t address = PointerToLowMemUInt32(object);
1343 DCHECK_LE(offset + 4, code->size());
1344 uint8_t* data = &(*code)[offset];
1345 data[0] = address & 0xffu;
1346 data[1] = (address >> 8) & 0xffu;
1347 data[2] = (address >> 16) & 0xffu;
1348 data[3] = (address >> 24) & 0xffu;
1349 }
1350
Mathieu Chartiere401d142015-04-22 13:56:20 -07001351 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001352 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001353 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001354 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001355 } else if (kIsDebugBuild) {
1356 // NOTE: We're using linker patches for app->boot references when the image can
1357 // be relocated and therefore we need to emit .oat_patches. We're not using this
1358 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001359 std::vector<gc::space::ImageSpace*> image_spaces =
1360 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1361 bool contains_method = false;
1362 for (gc::space::ImageSpace* image_space : image_spaces) {
1363 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1364 contains_method |=
1365 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1366 }
1367 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001368 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001369 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001370 uint32_t address = PointerToLowMemUInt32(method);
1371 DCHECK_LE(offset + 4, code->size());
1372 uint8_t* data = &(*code)[offset];
1373 data[0] = address & 0xffu;
1374 data[1] = (address >> 8) & 0xffu;
1375 data[2] = (address >> 16) & 0xffu;
1376 data[3] = (address >> 24) & 0xffu;
1377 }
1378
Vladimir Markof4da6752014-08-01 19:04:18 +01001379 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001380 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001381 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001382 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001383 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1384 // TODO: Clean up offset types.
1385 // The target_offset must be treated as signed for cross-oat patching.
1386 const void* target = reinterpret_cast<const void*>(
1387 writer_->image_writer_->GetOatDataBegin(oat_index) +
1388 static_cast<int32_t>(target_offset));
1389 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001390 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001391 DCHECK_LE(offset + 4, code->size());
1392 uint8_t* data = &(*code)[offset];
1393 data[0] = address & 0xffu;
1394 data[1] = (address >> 8) & 0xffu;
1395 data[2] = (address >> 16) & 0xffu;
1396 data[3] = (address >> 24) & 0xffu;
1397 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001398};
1399
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001400class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1401 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001402 WriteMapMethodVisitor(OatWriter* writer,
1403 OutputStream* out,
1404 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001405 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001406 : OatDexMethodVisitor(writer, relative_offset),
1407 out_(out),
1408 file_offset_(file_offset) {
1409 }
1410
1411 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001412 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001413 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1414
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001415 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001416 size_t file_offset = file_offset_;
1417 OutputStream* out = out_;
1418
Mingyao Yang063fc772016-08-02 11:02:54 -07001419 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001420 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001421 ++method_offsets_index_;
1422
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001423 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1424 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1425 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001426 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001427
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001428 // If vdex is enabled, only emit the map for compiled code. The quickening info
1429 // is emitted in the vdex already.
1430 if (map_offset != 0u &&
1431 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001432 // Transform map_offset to actual oat data offset.
1433 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1434 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001435 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001436
1437 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1438 size_t map_size = map.size() * sizeof(map[0]);
1439 if (map_offset == offset_) {
1440 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001441 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001442 ReportWriteFailure(it);
1443 return false;
1444 }
1445 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001446 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001447 }
1448 DCHECK_OFFSET_();
1449 }
1450
1451 return true;
1452 }
1453
1454 private:
1455 OutputStream* const out_;
1456 size_t const file_offset_;
1457
1458 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001459 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001460 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001461 }
1462};
1463
1464// Visit all methods from all classes in all dex files with the specified visitor.
1465bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1466 for (const DexFile* dex_file : *dex_files_) {
1467 const size_t class_def_count = dex_file->NumClassDefs();
1468 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1469 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1470 return false;
1471 }
1472 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001473 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001474 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001475 ClassDataItemIterator it(*dex_file, class_data);
1476 while (it.HasNextStaticField()) {
1477 it.Next();
1478 }
1479 while (it.HasNextInstanceField()) {
1480 it.Next();
1481 }
1482 size_t class_def_method_index = 0u;
1483 while (it.HasNextDirectMethod()) {
1484 if (!visitor->VisitMethod(class_def_method_index, it)) {
1485 return false;
1486 }
1487 ++class_def_method_index;
1488 it.Next();
1489 }
1490 while (it.HasNextVirtualMethod()) {
1491 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1492 return false;
1493 }
1494 ++class_def_method_index;
1495 it.Next();
1496 }
1497 }
1498 if (UNLIKELY(!visitor->EndClass())) {
1499 return false;
1500 }
1501 }
1502 }
1503 return true;
1504}
1505
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001506size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1507 const InstructionSetFeatures* instruction_set_features,
1508 uint32_t num_dex_files,
1509 SafeMap<std::string, std::string>* key_value_store) {
1510 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1511 oat_header_.reset(OatHeader::Create(instruction_set,
1512 instruction_set_features,
1513 num_dex_files,
1514 key_value_store));
1515 size_oat_header_ += sizeof(OatHeader);
1516 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001517 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001518}
1519
1520size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001521 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1522 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001523 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001524 oat_dex_file.offset_ = offset;
1525 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001526 }
1527 return offset;
1528}
1529
Brian Carlstrom389efb02012-01-11 12:06:26 -08001530size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001531 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001532 InitOatClassesMethodVisitor visitor(this, offset);
1533 bool success = VisitDexMethods(&visitor);
1534 CHECK(success);
1535 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001536
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001537 // Update oat_dex_files_.
1538 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001539 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1540 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001541 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001542 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001543 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001544 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001545 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001546 CHECK(oat_class_it == oat_classes_.end());
1547
1548 return offset;
1549}
1550
1551size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001552 InitMapMethodVisitor visitor(this, offset);
1553 bool success = VisitDexMethods(&visitor);
1554 DCHECK(success);
1555 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001556
Brian Carlstrome24fa612011-09-29 00:53:55 -07001557 return offset;
1558}
1559
1560size_t OatWriter::InitOatCode(size_t offset) {
1561 // calculate the offsets within OatHeader to executable code
1562 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001563 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001564 // required to be on a new page boundary
1565 offset = RoundUp(offset, kPageSize);
1566 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001567 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001568 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001569 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001570
Ian Rogers848871b2013-08-05 10:56:33 -07001571 #define DO_TRAMPOLINE(field, fn_name) \
1572 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001573 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1574 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001575 (field) = compiler_driver_->Create ## fn_name(); \
1576 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001577
Ian Rogers848871b2013-08-05 10:56:33 -07001578 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001579 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001580 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001581 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1582 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001583
Ian Rogers848871b2013-08-05 10:56:33 -07001584 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001585 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001586 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1587 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1588 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001589 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001590 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001591 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001592 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001593 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001594 return offset;
1595}
1596
1597size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001598 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1599 bool success = VisitDexMethods(&code_visitor);
1600 DCHECK(success);
1601 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001602
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001603 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001604 InitImageMethodVisitor image_visitor(this, offset);
1605 success = VisitDexMethods(&image_visitor);
1606 DCHECK(success);
1607 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001608 }
Logan Chien8b977d32012-02-21 19:14:55 +08001609
Brian Carlstrome24fa612011-09-29 00:53:55 -07001610 return offset;
1611}
1612
Vladimir Markoaad75c62016-10-03 08:46:48 +00001613void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1614 DCHECK(!HasBootImage());
1615
1616 // Allocate space for app dex cache arrays in the .bss section.
1617 bss_start_ = RoundUp(oat_size_, kPageSize);
1618 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1619 bss_size_ = 0u;
1620 for (const DexFile* dex_file : *dex_files_) {
1621 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1622 DexCacheArraysLayout layout(pointer_size, dex_file);
1623 bss_size_ += layout.Size();
1624 }
1625
1626 bss_roots_offset_ = bss_size_;
1627
1628 // Prepare offsets for .bss String entries.
1629 for (auto& entry : bss_string_entries_) {
1630 DCHECK_EQ(entry.second, 0u);
1631 entry.second = bss_start_ + bss_size_;
1632 bss_size_ += sizeof(GcRoot<mirror::String>);
1633 }
1634}
1635
David Srbeckybc90fd02015-04-22 19:40:27 +01001636bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001637 CHECK(write_state_ == WriteState::kWriteRoData);
1638
Vladimir Markoe079e212016-05-25 12:49:49 +01001639 // Wrap out to update checksum with each write.
1640 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1641 out = &checksum_updating_out;
1642
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001643 if (!WriteClassOffsets(out)) {
1644 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001645 return false;
1646 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001647
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001648 if (!WriteClasses(out)) {
1649 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001650 return false;
1651 }
1652
Vladimir Markof4da6752014-08-01 19:04:18 +01001653 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001654 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001655 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001656 return false;
1657 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001658 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001659 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001660 relative_offset = WriteMaps(out, file_offset, relative_offset);
1661 if (relative_offset == 0) {
1662 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1663 return false;
1664 }
1665
David Srbeckybc90fd02015-04-22 19:40:27 +01001666 // Write padding.
1667 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1668 relative_offset += size_executable_offset_alignment_;
1669 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1670 size_t expected_file_offset = file_offset + relative_offset;
1671 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1672 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1673 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1674 return 0;
1675 }
1676 DCHECK_OFFSET();
1677
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001678 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001679 return true;
1680}
1681
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001682class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1683 public:
1684 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1685 : DexMethodVisitor(writer, offset),
1686 out_(out),
1687 written_bytes_(0u) {}
1688
1689 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1690 const ClassDataItemIterator& it) {
1691 if (it.GetMethodCodeItem() == nullptr) {
1692 // No CodeItem. Native or abstract method.
1693 return true;
1694 }
1695
1696 uint32_t method_idx = it.GetMemberIndex();
1697 CompiledMethod* compiled_method =
1698 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1699
1700 uint32_t length = 0;
1701 const uint8_t* data = nullptr;
1702 // VMap only contains quickening info if this method is not compiled.
1703 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1704 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1705 data = map.data();
1706 length = map.size() * sizeof(map.front());
1707 }
1708
1709 if (!out_->WriteFully(&length, sizeof(length)) ||
1710 !out_->WriteFully(data, length)) {
1711 PLOG(ERROR) << "Failed to write quickening info for "
1712 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1713 return false;
1714 }
1715 offset_ += sizeof(length) + length;
1716 written_bytes_ += sizeof(length) + length;
1717 return true;
1718 }
1719
1720 size_t GetNumberOfWrittenBytes() const {
1721 return written_bytes_;
1722 }
1723
1724 private:
1725 OutputStream* const out_;
1726 size_t written_bytes_;
1727};
1728
1729bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1730 if (!kIsVdexEnabled) {
1731 return true;
1732 }
1733
1734 size_t initial_offset = vdex_size_;
1735 size_t start_offset = RoundUp(initial_offset, 4u);
1736
1737 vdex_size_ = start_offset;
1738 vdex_quickening_info_offset_ = vdex_size_;
1739 size_quickening_info_alignment_ = start_offset - initial_offset;
1740
1741 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1742 if (actual_offset != static_cast<off_t>(start_offset)) {
1743 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1744 << " Expected: " << start_offset
1745 << " Output: " << vdex_out->GetLocation();
1746 return false;
1747 }
1748
1749 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1750 if (!VisitDexMethods(&visitor)) {
1751 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1752 return false;
1753 }
1754
1755 if (!vdex_out->Flush()) {
1756 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1757 << " File: " << vdex_out->GetLocation();
1758 return false;
1759 }
1760
1761 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1762 vdex_size_ += size_quickening_info_;
1763 return true;
1764}
1765
David Brazdil5d5a36b2016-09-14 15:34:10 +01001766bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1767 if (!kIsVdexEnabled) {
1768 return true;
1769 }
1770
1771 if (verifier_deps == nullptr) {
1772 // Nothing to write. Record the offset, but no need
1773 // for alignment.
1774 vdex_verifier_deps_offset_ = vdex_size_;
1775 return true;
1776 }
1777
1778 size_t initial_offset = vdex_size_;
1779 size_t start_offset = RoundUp(initial_offset, 4u);
1780
1781 vdex_size_ = start_offset;
1782 vdex_verifier_deps_offset_ = vdex_size_;
1783 size_verifier_deps_alignment_ = start_offset - initial_offset;
1784
1785 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1786 if (actual_offset != static_cast<off_t>(start_offset)) {
1787 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1788 << " Expected: " << start_offset
1789 << " Output: " << vdex_out->GetLocation();
1790 return false;
1791 }
1792
1793 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001794 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001795
1796 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1797 PLOG(ERROR) << "Failed to write verifier deps."
1798 << " File: " << vdex_out->GetLocation();
1799 return false;
1800 }
1801 if (!vdex_out->Flush()) {
1802 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1803 << " File: " << vdex_out->GetLocation();
1804 return false;
1805 }
1806
1807 size_verifier_deps_ = buffer.size();
1808 vdex_size_ += size_verifier_deps_;
1809 return true;
1810}
1811
David Srbeckybc90fd02015-04-22 19:40:27 +01001812bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001813 CHECK(write_state_ == WriteState::kWriteText);
1814
Vladimir Markoe079e212016-05-25 12:49:49 +01001815 // Wrap out to update checksum with each write.
1816 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1817 out = &checksum_updating_out;
1818
Vladimir Marko944da602016-02-19 12:27:55 +00001819 SetMultiOatRelativePatcherAdjustment();
1820
David Srbeckybc90fd02015-04-22 19:40:27 +01001821 const size_t file_offset = oat_data_offset_;
1822 size_t relative_offset = oat_header_->GetExecutableOffset();
1823 DCHECK_OFFSET();
1824
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001825 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001826 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001827 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001828 return false;
1829 }
1830
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001831 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1832 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001833 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001834 return false;
1835 }
1836
Vladimir Markof4da6752014-08-01 19:04:18 +01001837 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001838 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001839 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1840 return false;
1841 }
1842
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001843 if (kIsDebugBuild) {
1844 uint32_t size_total = 0;
1845 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001846 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1847 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001848
David Brazdil7b49e6c2016-09-01 11:06:18 +01001849 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001850 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001851 DO_STAT(size_dex_file_alignment_);
1852 DO_STAT(size_executable_offset_alignment_);
1853 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001854 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001855 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001856 DO_STAT(size_verifier_deps_);
1857 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001858 DO_STAT(size_quickening_info_);
1859 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001860 DO_STAT(size_interpreter_to_interpreter_bridge_);
1861 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1862 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001863 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001864 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001865 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001866 DO_STAT(size_quick_to_interpreter_bridge_);
1867 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001868 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001869 DO_STAT(size_code_);
1870 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001871 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001872 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001873 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001874 DO_STAT(size_oat_dex_file_location_size_);
1875 DO_STAT(size_oat_dex_file_location_data_);
1876 DO_STAT(size_oat_dex_file_location_checksum_);
1877 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001878 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001879 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001880 DO_STAT(size_oat_lookup_table_alignment_);
1881 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001882 DO_STAT(size_oat_class_offsets_alignment_);
1883 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001884 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001885 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001886 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001887 DO_STAT(size_oat_class_method_offsets_);
1888 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001889
David Brazdil7b49e6c2016-09-01 11:06:18 +01001890 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1891
1892 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1893 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001894 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001895
David Brazdil7b49e6c2016-09-01 11:06:18 +01001896 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1897 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001898
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001899 write_state_ = WriteState::kWriteHeader;
1900 return true;
1901}
1902
1903bool OatWriter::WriteHeader(OutputStream* out,
1904 uint32_t image_file_location_oat_checksum,
1905 uintptr_t image_file_location_oat_begin,
1906 int32_t image_patch_delta) {
1907 CHECK(write_state_ == WriteState::kWriteHeader);
1908
1909 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1910 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001911 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001912 CHECK_EQ(image_patch_delta, 0);
1913 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1914 } else {
1915 CHECK_ALIGNED(image_patch_delta, kPageSize);
1916 oat_header_->SetImagePatchDelta(image_patch_delta);
1917 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001918 oat_header_->UpdateChecksumWithHeaderData();
1919
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001920 const size_t file_offset = oat_data_offset_;
1921
1922 off_t current_offset = out->Seek(0, kSeekCurrent);
1923 if (current_offset == static_cast<off_t>(-1)) {
1924 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1925 return false;
1926 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001927 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001928 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1929 return false;
1930 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001931 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001932
1933 // Flush all other data before writing the header.
1934 if (!out->Flush()) {
1935 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1936 return false;
1937 }
1938 // Write the header.
1939 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001940 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001941 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1942 return false;
1943 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001944 // Flush the header data.
1945 if (!out->Flush()) {
1946 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001947 return false;
1948 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001949
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001950 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1951 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1952 return false;
1953 }
1954 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1955
1956 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001957 return true;
1958}
1959
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001960bool OatWriter::WriteClassOffsets(OutputStream* out) {
1961 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1962 if (oat_dex_file.class_offsets_offset_ != 0u) {
1963 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1964 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1965 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1966 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1967 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001968 return false;
1969 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001970 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1971 return false;
1972 }
1973 }
1974 }
1975 return true;
1976}
1977
1978bool OatWriter::WriteClasses(OutputStream* out) {
1979 for (OatClass& oat_class : oat_classes_) {
1980 if (!oat_class.Write(this, out, oat_data_offset_)) {
1981 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1982 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001983 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001984 }
1985 return true;
1986}
1987
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001988size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001989 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001990 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1991 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1992 return 0;
1993 }
1994 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001995 size_vmap_table_ = relative_offset - vmap_tables_offset;
1996
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001997 return relative_offset;
1998}
1999
2000size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002001 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002002 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002003
Ian Rogers848871b2013-08-05 10:56:33 -07002004 #define DO_TRAMPOLINE(field) \
2005 do { \
2006 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2007 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002008 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002009 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002010 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002011 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002012 return false; \
2013 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002014 size_ ## field += (field)->size(); \
2015 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002016 DCHECK_OFFSET(); \
2017 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002018
Ian Rogers848871b2013-08-05 10:56:33 -07002019 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002020 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002021 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002022 DO_TRAMPOLINE(quick_resolution_trampoline_);
2023 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2024 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002025 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002026 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002027}
2028
Ian Rogers3d504072014-03-01 09:16:49 -08002029size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002030 const size_t file_offset,
2031 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002032 #define VISIT(VisitorType) \
2033 do { \
2034 VisitorType visitor(this, out, file_offset, relative_offset); \
2035 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2036 return 0; \
2037 } \
2038 relative_offset = visitor.GetOffset(); \
2039 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002040
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002041 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002042
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002043 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002044
Vladimir Markob163bb72015-03-31 21:49:49 +01002045 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2046 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2047 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2048
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002049 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002050}
2051
Vladimir Marko944da602016-02-19 12:27:55 +00002052bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002053 // Get the elf file offset of the oat file.
2054 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2055 if (raw_file_offset == static_cast<off_t>(-1)) {
2056 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2057 return false;
2058 }
2059 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2060 return true;
2061}
2062
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002063bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2064 // Read the dex file header and perform minimal verification.
2065 uint8_t raw_header[sizeof(DexFile::Header)];
2066 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2067 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2068 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2069 return false;
2070 }
2071 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2072 return false;
2073 }
2074
2075 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2076 oat_dex_file->dex_file_size_ = header->file_size_;
2077 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2078 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2079 return true;
2080}
2081
2082bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2083 if (!DexFile::IsMagicValid(raw_header)) {
2084 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2085 return false;
2086 }
2087 if (!DexFile::IsVersionValid(raw_header)) {
2088 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2089 return false;
2090 }
2091 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2092 if (header->file_size_ < sizeof(DexFile::Header)) {
2093 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2094 << " File: " << location;
2095 return false;
2096 }
2097 return true;
2098}
2099
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002100bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002101 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002102
David Brazdil7b49e6c2016-09-01 11:06:18 +01002103 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002104
2105 // Write dex files.
2106 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002107 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002108 return false;
2109 }
2110 }
2111
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002112 CloseSources();
2113 return true;
2114}
2115
2116void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002117 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2118 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2119 }
2120 zipped_dex_files_.clear();
2121 zip_archives_.clear();
2122 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002123}
2124
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002125bool OatWriter::WriteDexFile(OutputStream* out,
2126 File* file,
2127 OatDexFile* oat_dex_file,
2128 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002129 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002130 return false;
2131 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002132 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002133 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002134 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2135 return false;
2136 }
2137 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002138 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002139 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002140 return false;
2141 }
2142 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002143 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002144 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002145 return false;
2146 }
2147 } else {
2148 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002149 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002150 return false;
2151 }
2152 }
2153
2154 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002155 if (kIsVdexEnabled) {
2156 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2157 vdex_size_ += oat_dex_file->dex_file_size_;
2158 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002159 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002160 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2161 oat_size_ += oat_dex_file->dex_file_size_;
2162 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002163 size_dex_file_ += oat_dex_file->dex_file_size_;
2164 return true;
2165}
2166
2167bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2168 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002169 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2170 size_t start_offset = RoundUp(initial_offset, 4);
2171 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2172 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002173
2174 // Seek to the start of the dex file and flush any pending operations in the stream.
2175 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002176 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2177 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002178 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002179 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002180 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2181 return false;
2182 }
2183 if (!out->Flush()) {
2184 PLOG(ERROR) << "Failed to flush before writing dex file."
2185 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2186 return false;
2187 }
2188 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002189 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002190 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002191 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002192 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2193 return false;
2194 }
2195
David Brazdil7b49e6c2016-09-01 11:06:18 +01002196 if (kIsVdexEnabled) {
2197 vdex_size_ = start_offset;
2198 } else {
2199 oat_size_ = start_offset;
2200 }
2201 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002202 return true;
2203}
2204
Jeff Hao608f2ce2016-10-19 11:17:11 -07002205bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2206 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2207 std::string error_msg;
2208 std::string location(oat_dex_file->GetLocation());
2209 std::unique_ptr<const DexFile> dex_file;
2210 if (oat_dex_file->source_.IsZipEntry()) {
2211 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2212 std::unique_ptr<MemMap> mem_map(
2213 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2214 dex_file = DexFile::Open(location,
2215 zip_entry->GetCrc32(),
2216 std::move(mem_map),
2217 /* verify */ true,
2218 /* verify_checksum */ true,
2219 &error_msg);
2220 } else {
2221 DCHECK(oat_dex_file->source_.IsRawFile());
2222 File* raw_file = oat_dex_file->source_.GetRawFile();
2223 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2224 }
2225 Options options;
2226 options.output_to_memmap_ = true;
2227 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2228 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2229 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002230 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002231 return false;
2232 }
2233 // Set the checksum of the new oat dex file to be the original file's checksum.
2234 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2235 return true;
2236}
2237
David Brazdil7b49e6c2016-09-01 11:06:18 +01002238bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002239 File* file,
2240 OatDexFile* oat_dex_file,
2241 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002242 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2243 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002244
2245 // Extract the dex file and get the extracted size.
2246 std::string error_msg;
2247 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2248 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2249 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2250 return false;
2251 }
2252 if (file->Flush() != 0) {
2253 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2254 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2255 return false;
2256 }
2257 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2258 if (extracted_end == static_cast<off_t>(-1)) {
2259 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2260 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2261 return false;
2262 }
2263 if (extracted_end < static_cast<off_t>(start_offset)) {
2264 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2265 << " Start: " << start_offset
2266 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2267 return false;
2268 }
2269 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2270 if (extracted_size < sizeof(DexFile::Header)) {
2271 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2272 << extracted_size << " File: " << oat_dex_file->GetLocation();
2273 return false;
2274 }
2275
2276 // Read the dex file header and extract required data to OatDexFile.
2277 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2278 if (actual_offset != static_cast<off_t>(start_offset)) {
2279 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2280 << " Expected: " << start_offset
2281 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2282 return false;
2283 }
2284 if (!ReadDexFileHeader(file, oat_dex_file)) {
2285 return false;
2286 }
2287 if (extracted_size < oat_dex_file->dex_file_size_) {
2288 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2289 << " file size from header: " << oat_dex_file->dex_file_size_
2290 << " File: " << oat_dex_file->GetLocation();
2291 return false;
2292 }
2293
2294 // Override the checksum from header with the CRC from ZIP entry.
2295 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2296
2297 // Seek both file and stream to the end offset.
2298 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2299 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2300 if (actual_offset != static_cast<off_t>(end_offset)) {
2301 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2302 << " Expected: " << end_offset
2303 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2304 return false;
2305 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002306 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002307 if (actual_offset != static_cast<off_t>(end_offset)) {
2308 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2309 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2310 return false;
2311 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002312 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002313 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2314 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2315 return false;
2316 }
2317
2318 // If we extracted more than the size specified in the header, truncate the file.
2319 if (extracted_size > oat_dex_file->dex_file_size_) {
2320 if (file->SetLength(end_offset) != 0) {
2321 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002322 << " File: " << oat_dex_file->GetLocation()
2323 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002324 return false;
2325 }
2326 }
2327
2328 return true;
2329}
2330
David Brazdil7b49e6c2016-09-01 11:06:18 +01002331bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002332 File* file,
2333 OatDexFile* oat_dex_file,
2334 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002335 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2336 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002337
2338 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2339 if (input_offset != static_cast<off_t>(0)) {
2340 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2341 << " Expected: 0"
2342 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2343 return false;
2344 }
2345 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2346 return false;
2347 }
2348
2349 // Copy the input dex file using sendfile().
2350 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2351 PLOG(ERROR) << "Failed to copy dex file to oat file."
2352 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2353 return false;
2354 }
2355 if (file->Flush() != 0) {
2356 PLOG(ERROR) << "Failed to flush dex file."
2357 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2358 return false;
2359 }
2360
2361 // Check file position and seek the stream to the end offset.
2362 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2363 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2364 if (actual_offset != static_cast<off_t>(end_offset)) {
2365 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2366 << " Expected: " << end_offset
2367 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2368 return false;
2369 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002370 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002371 if (actual_offset != static_cast<off_t>(end_offset)) {
2372 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2373 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2374 return false;
2375 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002376 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002377 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2378 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2379 return false;
2380 }
2381
2382 return true;
2383}
2384
David Brazdil7b49e6c2016-09-01 11:06:18 +01002385bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002386 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002387 const uint8_t* dex_file,
2388 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002389 // Note: The raw data has already been checked to contain the header
2390 // and all the data that the header specifies as the file size.
2391 DCHECK(dex_file != nullptr);
2392 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2393 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2394
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002395 if (update_input_vdex) {
2396 // The vdex already contains the dex code, no need to write it again.
2397 } else {
2398 if (!out->WriteFully(dex_file, header->file_size_)) {
2399 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2400 << " to " << out->GetLocation();
2401 return false;
2402 }
2403 if (!out->Flush()) {
2404 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2405 << " File: " << oat_dex_file->GetLocation();
2406 return false;
2407 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002408 }
2409
2410 // Update dex file size and resize class offsets in the OatDexFile.
2411 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002412 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002413 oat_dex_file->dex_file_size_ = header->file_size_;
2414 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2415 return true;
2416}
2417
2418bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2419 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2420
David Brazdil181e1cc2016-09-01 16:38:47 +00002421 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2422 if (initial_offset == static_cast<off_t>(-1)) {
2423 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2424 return false;
2425 }
2426
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002427 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2428 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2429 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2430 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2431 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2432 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2433 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2434 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2435 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2436 return false;
2437 }
2438
2439 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2440 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2441
2442 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2443 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2444
2445 // Write OatDexFile.
2446 if (!oat_dex_file->Write(this, rodata)) {
2447 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2448 return false;
2449 }
2450 }
2451
David Brazdil181e1cc2016-09-01 16:38:47 +00002452 // Seek back to the initial position.
2453 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2454 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2455 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2456 return false;
2457 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002458
David Brazdilb92ba622016-09-01 16:00:30 +00002459 return true;
2460}
2461
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002462bool OatWriter::OpenDexFiles(
2463 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002464 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002465 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2466 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2467 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2468
2469 if (oat_dex_files_.empty()) {
2470 // Nothing to do.
2471 return true;
2472 }
2473
2474 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002475 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2476
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002477 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002478 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2479 length,
2480 PROT_READ | PROT_WRITE,
2481 MAP_SHARED,
2482 file->Fd(),
2483 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2484 /* low_4gb */ false,
2485 file->GetPath().c_str(),
2486 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002487 if (dex_files_map == nullptr) {
2488 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2489 << " error: " << error_msg;
2490 return false;
2491 }
2492 std::vector<std::unique_ptr<const DexFile>> dex_files;
2493 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2494 // Make sure no one messed with input files while we were copying data.
2495 // At the very least we need consistent file size and number of class definitions.
2496 const uint8_t* raw_dex_file =
2497 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2498 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2499 // Note: ValidateDexFileHeader() already logged an error message.
2500 LOG(ERROR) << "Failed to verify written dex file header!"
2501 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2502 << " ~ " << static_cast<const void*>(raw_dex_file);
2503 return false;
2504 }
2505 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2506 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2507 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2508 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2509 << " Output: " << file->GetPath();
2510 return false;
2511 }
2512 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2513 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2514 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2515 << " Output: " << file->GetPath();
2516 return false;
2517 }
2518
2519 // Now, open the dex file.
2520 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2521 oat_dex_file.dex_file_size_,
2522 oat_dex_file.GetLocation(),
2523 oat_dex_file.dex_file_location_checksum_,
2524 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002525 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002526 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002527 &error_msg));
2528 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002529 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2530 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002531 return false;
2532 }
2533 }
2534
2535 *opened_dex_files_map = std::move(dex_files_map);
2536 *opened_dex_files = std::move(dex_files);
2537 return true;
2538}
2539
2540bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002541 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002542 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2543 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2544
David Brazdil7b49e6c2016-09-01 11:06:18 +01002545 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2546 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2547 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2548 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2549 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2550 return false;
2551 }
2552
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002553 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2554 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2555 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002556 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2557
2558 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2559 oat_dex_file->class_offsets_.empty()) {
2560 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002561 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002562
2563 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2564 if (table_size == 0u) {
2565 continue;
2566 }
2567
2568 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002569 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002570 const DexFile& dex_file = *opened_dex_files[i];
2571 {
2572 std::unique_ptr<TypeLookupTable> type_lookup_table =
2573 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2574 type_lookup_table_oat_dex_files_.push_back(
2575 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2576 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2577 }
2578 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002579
2580 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002581 size_t initial_offset = oat_size_;
2582 size_t rodata_offset = RoundUp(initial_offset, 4);
2583 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002584
2585 if (padding_size != 0u) {
2586 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002587 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002588 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2589 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002590 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002591 return false;
2592 }
2593 }
2594
2595 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002596 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002597 DCHECK_EQ(table_size, table->RawDataLength());
2598
David Brazdil7b49e6c2016-09-01 11:06:18 +01002599 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002600 PLOG(ERROR) << "Failed to write lookup table."
2601 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002602 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002603 return false;
2604 }
2605
2606 oat_dex_file->lookup_table_offset_ = rodata_offset;
2607
David Brazdil7b49e6c2016-09-01 11:06:18 +01002608 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002609 size_oat_lookup_table_ += table_size;
2610 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002611 }
2612
David Brazdil7b49e6c2016-09-01 11:06:18 +01002613 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002614 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002615 << " File: " << oat_rodata->GetLocation();
2616 return false;
2617 }
2618
2619 return true;
2620}
2621
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002622bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002623 if (!kIsVdexEnabled) {
2624 return true;
2625 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002626 // Write checksums
2627 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2628 if (actual_offset != sizeof(VdexFile::Header)) {
2629 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2630 << " File: " << vdex_out->GetLocation();
2631 return false;
2632 }
2633
2634 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2635 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2636 if (!vdex_out->WriteFully(
2637 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2638 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2639 << vdex_out->GetLocation();
2640 return false;
2641 }
2642 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2643 }
2644
2645 // Write header.
2646 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002647 if (actual_offset != 0) {
2648 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2649 << " File: " << vdex_out->GetLocation();
2650 return false;
2651 }
2652
David Brazdil5d5a36b2016-09-14 15:34:10 +01002653 DCHECK_NE(vdex_dex_files_offset_, 0u);
2654 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2655
2656 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002657 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2658 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002659
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002660 VdexFile::Header vdex_header(oat_dex_files_.size(),
2661 dex_section_size,
2662 verifier_deps_section_size,
2663 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002664 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2665 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002666 return false;
2667 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002668 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002669
David Brazdil5d5a36b2016-09-14 15:34:10 +01002670 if (!vdex_out->Flush()) {
2671 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2672 << " File: " << vdex_out->GetLocation();
2673 return false;
2674 }
2675
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002676 return true;
2677}
2678
Vladimir Markof4da6752014-08-01 19:04:18 +01002679bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2680 static const uint8_t kPadding[] = {
2681 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2682 };
2683 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002684 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002685 return false;
2686 }
2687 size_code_alignment_ += aligned_code_delta;
2688 return true;
2689}
2690
Vladimir Marko944da602016-02-19 12:27:55 +00002691void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2692 DCHECK(dex_files_ != nullptr);
2693 DCHECK(relative_patcher_ != nullptr);
2694 DCHECK_NE(oat_data_offset_, 0u);
2695 if (image_writer_ != nullptr && !dex_files_->empty()) {
2696 // The oat data begin may not be initialized yet but the oat file offset is ready.
2697 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2698 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2699 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002700 }
2701}
2702
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002703OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2704 DexFileSource source,
2705 CreateTypeLookupTable create_type_lookup_table)
2706 : source_(source),
2707 create_type_lookup_table_(create_type_lookup_table),
2708 dex_file_size_(0),
2709 offset_(0),
2710 dex_file_location_size_(strlen(dex_file_location)),
2711 dex_file_location_data_(dex_file_location),
2712 dex_file_location_checksum_(0u),
2713 dex_file_offset_(0u),
2714 class_offsets_offset_(0u),
2715 lookup_table_offset_(0u),
2716 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002717}
2718
2719size_t OatWriter::OatDexFile::SizeOf() const {
2720 return sizeof(dex_file_location_size_)
2721 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002722 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002723 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002724 + sizeof(class_offsets_offset_)
2725 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002726}
2727
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002728void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2729 DCHECK_EQ(class_offsets_offset_, 0u);
2730 if (!class_offsets_.empty()) {
2731 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002732 size_t initial_offset = oat_writer->oat_size_;
2733 size_t offset = RoundUp(initial_offset, 4);
2734 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002735 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002736 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002737 }
2738}
2739
2740bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2741 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002742 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002743
Vladimir Markoe079e212016-05-25 12:49:49 +01002744 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002745 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002746 return false;
2747 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002748 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002749
Vladimir Markoe079e212016-05-25 12:49:49 +01002750 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002751 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002752 return false;
2753 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002754 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002755
Vladimir Markoe079e212016-05-25 12:49:49 +01002756 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002757 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002758 return false;
2759 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002760 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002761
Vladimir Markoe079e212016-05-25 12:49:49 +01002762 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002763 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002764 return false;
2765 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002766 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002767
Vladimir Markoe079e212016-05-25 12:49:49 +01002768 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002769 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2770 return false;
2771 }
2772 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2773
Vladimir Markoe079e212016-05-25 12:49:49 +01002774 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002775 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2776 return false;
2777 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002778 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002779
2780 return true;
2781}
2782
2783bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002784 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002785 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2786 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002787 return false;
2788 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002789 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002790 return true;
2791}
2792
Brian Carlstromba150c32013-08-27 17:31:03 -07002793OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002794 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002795 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002796 mirror::Class::Status status)
2797 : compiled_methods_(compiled_methods) {
2798 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002799 CHECK_LE(num_non_null_compiled_methods, num_methods);
2800
Brian Carlstrom265091e2013-01-30 14:08:26 -08002801 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002802 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2803
2804 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2805 // apply when there are 0 methods, we just arbitrarily say that 0
2806 // methods means kOatClassNoneCompiled and that we won't use
2807 // kOatClassAllCompiled unless there is at least one compiled
2808 // method. This means in an interpretter only system, we can assert
2809 // that all classes are kOatClassNoneCompiled.
2810 if (num_non_null_compiled_methods == 0) {
2811 type_ = kOatClassNoneCompiled;
2812 } else if (num_non_null_compiled_methods == num_methods) {
2813 type_ = kOatClassAllCompiled;
2814 } else {
2815 type_ = kOatClassSomeCompiled;
2816 }
2817
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002818 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002819 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002820 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002821
2822 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2823 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002824 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002825 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2826 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2827 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2828 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002829 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002830 method_bitmap_size_ = 0;
2831 }
2832
2833 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002834 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002835 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002836 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2837 } else {
2838 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2839 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2840 if (type_ == kOatClassSomeCompiled) {
2841 method_bitmap_->SetBit(i);
2842 }
2843 }
2844 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002845}
2846
Brian Carlstrom265091e2013-01-30 14:08:26 -08002847size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2848 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002849 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2850 if (method_offset == 0) {
2851 return 0;
2852 }
2853 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002854}
2855
2856size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2857 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002858 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002859}
2860
2861size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002862 return sizeof(status_)
2863 + sizeof(type_)
2864 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2865 + method_bitmap_size_
2866 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002867}
2868
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002869bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002870 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002871 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002872 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002873 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002874 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002875 return false;
2876 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002877 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002878
Vladimir Markoe079e212016-05-25 12:49:49 +01002879 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002880 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002881 return false;
2882 }
2883 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002884
Brian Carlstromba150c32013-08-27 17:31:03 -07002885 if (method_bitmap_size_ != 0) {
2886 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002887 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002888 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002889 return false;
2890 }
2891 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002892
Vladimir Markoe079e212016-05-25 12:49:49 +01002893 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002894 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002895 return false;
2896 }
2897 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2898 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002899
Vladimir Markoe079e212016-05-25 12:49:49 +01002900 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002901 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002902 return false;
2903 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002904 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002905 return true;
2906}
2907
Brian Carlstrome24fa612011-09-29 00:53:55 -07002908} // namespace art