blob: a9da09c82cb53f68fd5063a04c3d4fab0f977b0b [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 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001472 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1473 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1474 const uint8_t* class_data = dex_file->GetClassData(class_def);
1475 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1476 ClassDataItemIterator it(*dex_file, class_data);
1477 while (it.HasNextStaticField()) {
1478 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001479 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001480 while (it.HasNextInstanceField()) {
1481 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001482 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001483 size_t class_def_method_index = 0u;
1484 while (it.HasNextDirectMethod()) {
1485 if (!visitor->VisitMethod(class_def_method_index, it)) {
1486 return false;
1487 }
1488 ++class_def_method_index;
1489 it.Next();
1490 }
1491 while (it.HasNextVirtualMethod()) {
1492 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1493 return false;
1494 }
1495 ++class_def_method_index;
1496 it.Next();
1497 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001498 }
1499 }
1500 if (UNLIKELY(!visitor->EndClass())) {
1501 return false;
1502 }
1503 }
1504 }
1505 return true;
1506}
1507
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001508size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1509 const InstructionSetFeatures* instruction_set_features,
1510 uint32_t num_dex_files,
1511 SafeMap<std::string, std::string>* key_value_store) {
1512 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1513 oat_header_.reset(OatHeader::Create(instruction_set,
1514 instruction_set_features,
1515 num_dex_files,
1516 key_value_store));
1517 size_oat_header_ += sizeof(OatHeader);
1518 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001519 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001520}
1521
1522size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001523 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1524 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001525 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001526 oat_dex_file.offset_ = offset;
1527 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001528 }
1529 return offset;
1530}
1531
Brian Carlstrom389efb02012-01-11 12:06:26 -08001532size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001533 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001534 InitOatClassesMethodVisitor visitor(this, offset);
1535 bool success = VisitDexMethods(&visitor);
1536 CHECK(success);
1537 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001538
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001539 // Update oat_dex_files_.
1540 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001541 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1542 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001543 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001544 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001545 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001546 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001547 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001548 CHECK(oat_class_it == oat_classes_.end());
1549
1550 return offset;
1551}
1552
1553size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001554 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1555 return offset;
1556 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001557 InitMapMethodVisitor visitor(this, offset);
1558 bool success = VisitDexMethods(&visitor);
1559 DCHECK(success);
1560 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001561
Brian Carlstrome24fa612011-09-29 00:53:55 -07001562 return offset;
1563}
1564
1565size_t OatWriter::InitOatCode(size_t offset) {
1566 // calculate the offsets within OatHeader to executable code
1567 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001568 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001569 // required to be on a new page boundary
1570 offset = RoundUp(offset, kPageSize);
1571 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001572 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001573 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001574 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001575
Ian Rogers848871b2013-08-05 10:56:33 -07001576 #define DO_TRAMPOLINE(field, fn_name) \
1577 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001578 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1579 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001580 (field) = compiler_driver_->Create ## fn_name(); \
1581 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001582
Ian Rogers848871b2013-08-05 10:56:33 -07001583 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001584 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001585 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001586 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1587 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001588
Ian Rogers848871b2013-08-05 10:56:33 -07001589 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001590 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001591 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1592 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1593 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001594 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001595 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001596 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001597 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001598 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001599 return offset;
1600}
1601
1602size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001603 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1604 return offset;
1605 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001606 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1607 bool success = VisitDexMethods(&code_visitor);
1608 DCHECK(success);
1609 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001610
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001611 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001612 InitImageMethodVisitor image_visitor(this, offset);
1613 success = VisitDexMethods(&image_visitor);
1614 DCHECK(success);
1615 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001616 }
Logan Chien8b977d32012-02-21 19:14:55 +08001617
Brian Carlstrome24fa612011-09-29 00:53:55 -07001618 return offset;
1619}
1620
Vladimir Markoaad75c62016-10-03 08:46:48 +00001621void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1622 DCHECK(!HasBootImage());
1623
1624 // Allocate space for app dex cache arrays in the .bss section.
1625 bss_start_ = RoundUp(oat_size_, kPageSize);
1626 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1627 bss_size_ = 0u;
1628 for (const DexFile* dex_file : *dex_files_) {
1629 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1630 DexCacheArraysLayout layout(pointer_size, dex_file);
1631 bss_size_ += layout.Size();
1632 }
1633
1634 bss_roots_offset_ = bss_size_;
1635
1636 // Prepare offsets for .bss String entries.
1637 for (auto& entry : bss_string_entries_) {
1638 DCHECK_EQ(entry.second, 0u);
1639 entry.second = bss_start_ + bss_size_;
1640 bss_size_ += sizeof(GcRoot<mirror::String>);
1641 }
1642}
1643
David Srbeckybc90fd02015-04-22 19:40:27 +01001644bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001645 CHECK(write_state_ == WriteState::kWriteRoData);
1646
Vladimir Markoe079e212016-05-25 12:49:49 +01001647 // Wrap out to update checksum with each write.
1648 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1649 out = &checksum_updating_out;
1650
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001651 if (!WriteClassOffsets(out)) {
1652 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001653 return false;
1654 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001655
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001656 if (!WriteClasses(out)) {
1657 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001658 return false;
1659 }
1660
Vladimir Markof4da6752014-08-01 19:04:18 +01001661 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001662 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001663 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001664 return false;
1665 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001666 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001667 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001668 relative_offset = WriteMaps(out, file_offset, relative_offset);
1669 if (relative_offset == 0) {
1670 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1671 return false;
1672 }
1673
David Srbeckybc90fd02015-04-22 19:40:27 +01001674 // Write padding.
1675 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1676 relative_offset += size_executable_offset_alignment_;
1677 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1678 size_t expected_file_offset = file_offset + relative_offset;
1679 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1680 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1681 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1682 return 0;
1683 }
1684 DCHECK_OFFSET();
1685
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001686 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001687 return true;
1688}
1689
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001690class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1691 public:
1692 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1693 : DexMethodVisitor(writer, offset),
1694 out_(out),
1695 written_bytes_(0u) {}
1696
1697 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1698 const ClassDataItemIterator& it) {
1699 if (it.GetMethodCodeItem() == nullptr) {
1700 // No CodeItem. Native or abstract method.
1701 return true;
1702 }
1703
1704 uint32_t method_idx = it.GetMemberIndex();
1705 CompiledMethod* compiled_method =
1706 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1707
1708 uint32_t length = 0;
1709 const uint8_t* data = nullptr;
1710 // VMap only contains quickening info if this method is not compiled.
1711 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1712 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1713 data = map.data();
1714 length = map.size() * sizeof(map.front());
1715 }
1716
1717 if (!out_->WriteFully(&length, sizeof(length)) ||
1718 !out_->WriteFully(data, length)) {
1719 PLOG(ERROR) << "Failed to write quickening info for "
1720 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1721 return false;
1722 }
1723 offset_ += sizeof(length) + length;
1724 written_bytes_ += sizeof(length) + length;
1725 return true;
1726 }
1727
1728 size_t GetNumberOfWrittenBytes() const {
1729 return written_bytes_;
1730 }
1731
1732 private:
1733 OutputStream* const out_;
1734 size_t written_bytes_;
1735};
1736
1737bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1738 if (!kIsVdexEnabled) {
1739 return true;
1740 }
1741
1742 size_t initial_offset = vdex_size_;
1743 size_t start_offset = RoundUp(initial_offset, 4u);
1744
1745 vdex_size_ = start_offset;
1746 vdex_quickening_info_offset_ = vdex_size_;
1747 size_quickening_info_alignment_ = start_offset - initial_offset;
1748
1749 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1750 if (actual_offset != static_cast<off_t>(start_offset)) {
1751 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1752 << " Expected: " << start_offset
1753 << " Output: " << vdex_out->GetLocation();
1754 return false;
1755 }
1756
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001757 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1758 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1759 if (!VisitDexMethods(&visitor)) {
1760 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1761 return false;
1762 }
1763
1764 if (!vdex_out->Flush()) {
1765 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1766 << " File: " << vdex_out->GetLocation();
1767 return false;
1768 }
1769 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1770 } else {
1771 // We know we did not quicken.
1772 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001773 }
1774
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001775 vdex_size_ += size_quickening_info_;
1776 return true;
1777}
1778
David Brazdil5d5a36b2016-09-14 15:34:10 +01001779bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1780 if (!kIsVdexEnabled) {
1781 return true;
1782 }
1783
1784 if (verifier_deps == nullptr) {
1785 // Nothing to write. Record the offset, but no need
1786 // for alignment.
1787 vdex_verifier_deps_offset_ = vdex_size_;
1788 return true;
1789 }
1790
1791 size_t initial_offset = vdex_size_;
1792 size_t start_offset = RoundUp(initial_offset, 4u);
1793
1794 vdex_size_ = start_offset;
1795 vdex_verifier_deps_offset_ = vdex_size_;
1796 size_verifier_deps_alignment_ = start_offset - initial_offset;
1797
1798 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1799 if (actual_offset != static_cast<off_t>(start_offset)) {
1800 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1801 << " Expected: " << start_offset
1802 << " Output: " << vdex_out->GetLocation();
1803 return false;
1804 }
1805
1806 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001807 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001808
1809 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1810 PLOG(ERROR) << "Failed to write verifier deps."
1811 << " File: " << vdex_out->GetLocation();
1812 return false;
1813 }
1814 if (!vdex_out->Flush()) {
1815 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1816 << " File: " << vdex_out->GetLocation();
1817 return false;
1818 }
1819
1820 size_verifier_deps_ = buffer.size();
1821 vdex_size_ += size_verifier_deps_;
1822 return true;
1823}
1824
David Srbeckybc90fd02015-04-22 19:40:27 +01001825bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001826 CHECK(write_state_ == WriteState::kWriteText);
1827
Vladimir Markoe079e212016-05-25 12:49:49 +01001828 // Wrap out to update checksum with each write.
1829 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1830 out = &checksum_updating_out;
1831
Vladimir Marko944da602016-02-19 12:27:55 +00001832 SetMultiOatRelativePatcherAdjustment();
1833
David Srbeckybc90fd02015-04-22 19:40:27 +01001834 const size_t file_offset = oat_data_offset_;
1835 size_t relative_offset = oat_header_->GetExecutableOffset();
1836 DCHECK_OFFSET();
1837
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001838 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001839 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001840 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001841 return false;
1842 }
1843
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001844 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1845 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001846 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001847 return false;
1848 }
1849
Vladimir Markof4da6752014-08-01 19:04:18 +01001850 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001851 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001852 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1853 return false;
1854 }
1855
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001856 if (kIsDebugBuild) {
1857 uint32_t size_total = 0;
1858 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001859 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1860 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001861
David Brazdil7b49e6c2016-09-01 11:06:18 +01001862 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001863 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001864 DO_STAT(size_dex_file_alignment_);
1865 DO_STAT(size_executable_offset_alignment_);
1866 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001867 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001868 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001869 DO_STAT(size_verifier_deps_);
1870 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001871 DO_STAT(size_quickening_info_);
1872 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001873 DO_STAT(size_interpreter_to_interpreter_bridge_);
1874 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1875 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001876 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001877 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001878 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001879 DO_STAT(size_quick_to_interpreter_bridge_);
1880 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001881 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001882 DO_STAT(size_code_);
1883 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001884 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001885 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001886 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001887 DO_STAT(size_oat_dex_file_location_size_);
1888 DO_STAT(size_oat_dex_file_location_data_);
1889 DO_STAT(size_oat_dex_file_location_checksum_);
1890 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001891 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001892 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001893 DO_STAT(size_oat_lookup_table_alignment_);
1894 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001895 DO_STAT(size_oat_class_offsets_alignment_);
1896 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001897 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001898 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001899 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001900 DO_STAT(size_oat_class_method_offsets_);
1901 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001902
David Brazdil7b49e6c2016-09-01 11:06:18 +01001903 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1904
1905 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1906 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001907 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001908
David Brazdil7b49e6c2016-09-01 11:06:18 +01001909 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1910 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001911
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001912 write_state_ = WriteState::kWriteHeader;
1913 return true;
1914}
1915
1916bool OatWriter::WriteHeader(OutputStream* out,
1917 uint32_t image_file_location_oat_checksum,
1918 uintptr_t image_file_location_oat_begin,
1919 int32_t image_patch_delta) {
1920 CHECK(write_state_ == WriteState::kWriteHeader);
1921
1922 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1923 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001924 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001925 CHECK_EQ(image_patch_delta, 0);
1926 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1927 } else {
1928 CHECK_ALIGNED(image_patch_delta, kPageSize);
1929 oat_header_->SetImagePatchDelta(image_patch_delta);
1930 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001931 oat_header_->UpdateChecksumWithHeaderData();
1932
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001933 const size_t file_offset = oat_data_offset_;
1934
1935 off_t current_offset = out->Seek(0, kSeekCurrent);
1936 if (current_offset == static_cast<off_t>(-1)) {
1937 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1938 return false;
1939 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001940 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001941 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1942 return false;
1943 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001944 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001945
1946 // Flush all other data before writing the header.
1947 if (!out->Flush()) {
1948 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1949 return false;
1950 }
1951 // Write the header.
1952 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001953 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001954 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1955 return false;
1956 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001957 // Flush the header data.
1958 if (!out->Flush()) {
1959 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001960 return false;
1961 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001962
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001963 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1964 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1965 return false;
1966 }
1967 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1968
1969 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001970 return true;
1971}
1972
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001973bool OatWriter::WriteClassOffsets(OutputStream* out) {
1974 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1975 if (oat_dex_file.class_offsets_offset_ != 0u) {
1976 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1977 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1978 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1979 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1980 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001981 return false;
1982 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001983 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1984 return false;
1985 }
1986 }
1987 }
1988 return true;
1989}
1990
1991bool OatWriter::WriteClasses(OutputStream* out) {
1992 for (OatClass& oat_class : oat_classes_) {
1993 if (!oat_class.Write(this, out, oat_data_offset_)) {
1994 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1995 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001996 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001997 }
1998 return true;
1999}
2000
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002001size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002002 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002003 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2004 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2005 return 0;
2006 }
2007 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002008 size_vmap_table_ = relative_offset - vmap_tables_offset;
2009
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002010 return relative_offset;
2011}
2012
2013size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002014 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002015 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002016
Ian Rogers848871b2013-08-05 10:56:33 -07002017 #define DO_TRAMPOLINE(field) \
2018 do { \
2019 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2020 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002021 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002022 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002023 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002024 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002025 return false; \
2026 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002027 size_ ## field += (field)->size(); \
2028 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002029 DCHECK_OFFSET(); \
2030 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002031
Ian Rogers848871b2013-08-05 10:56:33 -07002032 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002033 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002034 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002035 DO_TRAMPOLINE(quick_resolution_trampoline_);
2036 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2037 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002038 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002039 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002040}
2041
Ian Rogers3d504072014-03-01 09:16:49 -08002042size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002043 const size_t file_offset,
2044 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002045 #define VISIT(VisitorType) \
2046 do { \
2047 VisitorType visitor(this, out, file_offset, relative_offset); \
2048 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2049 return 0; \
2050 } \
2051 relative_offset = visitor.GetOffset(); \
2052 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002053
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002054 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002055
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002056 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002057
Vladimir Markob163bb72015-03-31 21:49:49 +01002058 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2059 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2060 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2061
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002062 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002063}
2064
Vladimir Marko944da602016-02-19 12:27:55 +00002065bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002066 // Get the elf file offset of the oat file.
2067 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2068 if (raw_file_offset == static_cast<off_t>(-1)) {
2069 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2070 return false;
2071 }
2072 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2073 return true;
2074}
2075
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002076bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2077 // Read the dex file header and perform minimal verification.
2078 uint8_t raw_header[sizeof(DexFile::Header)];
2079 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2080 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2081 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2082 return false;
2083 }
2084 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2085 return false;
2086 }
2087
2088 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2089 oat_dex_file->dex_file_size_ = header->file_size_;
2090 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2091 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2092 return true;
2093}
2094
2095bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2096 if (!DexFile::IsMagicValid(raw_header)) {
2097 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2098 return false;
2099 }
2100 if (!DexFile::IsVersionValid(raw_header)) {
2101 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2102 return false;
2103 }
2104 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2105 if (header->file_size_ < sizeof(DexFile::Header)) {
2106 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2107 << " File: " << location;
2108 return false;
2109 }
2110 return true;
2111}
2112
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002113bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002114 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002115
David Brazdil7b49e6c2016-09-01 11:06:18 +01002116 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002117
2118 // Write dex files.
2119 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002120 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002121 return false;
2122 }
2123 }
2124
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002125 CloseSources();
2126 return true;
2127}
2128
2129void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002130 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2131 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2132 }
2133 zipped_dex_files_.clear();
2134 zip_archives_.clear();
2135 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002136}
2137
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002138bool OatWriter::WriteDexFile(OutputStream* out,
2139 File* file,
2140 OatDexFile* oat_dex_file,
2141 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002142 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002143 return false;
2144 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002145 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002146 DCHECK(!update_input_vdex);
Jeff Hao608f2ce2016-10-19 11:17:11 -07002147 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2148 return false;
2149 }
2150 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002151 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002152 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002153 return false;
2154 }
2155 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002156 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002157 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002158 return false;
2159 }
2160 } else {
2161 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002162 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002163 return false;
2164 }
2165 }
2166
2167 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002168 if (kIsVdexEnabled) {
2169 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2170 vdex_size_ += oat_dex_file->dex_file_size_;
2171 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002172 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002173 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2174 oat_size_ += oat_dex_file->dex_file_size_;
2175 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002176 size_dex_file_ += oat_dex_file->dex_file_size_;
2177 return true;
2178}
2179
2180bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2181 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002182 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2183 size_t start_offset = RoundUp(initial_offset, 4);
2184 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2185 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002186
2187 // Seek to the start of the dex file and flush any pending operations in the stream.
2188 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002189 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2190 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002191 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002192 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002193 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2194 return false;
2195 }
2196 if (!out->Flush()) {
2197 PLOG(ERROR) << "Failed to flush before writing dex file."
2198 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2199 return false;
2200 }
2201 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002202 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002203 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002204 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002205 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2206 return false;
2207 }
2208
David Brazdil7b49e6c2016-09-01 11:06:18 +01002209 if (kIsVdexEnabled) {
2210 vdex_size_ = start_offset;
2211 } else {
2212 oat_size_ = start_offset;
2213 }
2214 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002215 return true;
2216}
2217
Jeff Hao608f2ce2016-10-19 11:17:11 -07002218bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2219 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2220 std::string error_msg;
2221 std::string location(oat_dex_file->GetLocation());
2222 std::unique_ptr<const DexFile> dex_file;
2223 if (oat_dex_file->source_.IsZipEntry()) {
2224 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2225 std::unique_ptr<MemMap> mem_map(
2226 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2227 dex_file = DexFile::Open(location,
2228 zip_entry->GetCrc32(),
2229 std::move(mem_map),
2230 /* verify */ true,
2231 /* verify_checksum */ true,
2232 &error_msg);
2233 } else {
2234 DCHECK(oat_dex_file->source_.IsRawFile());
2235 File* raw_file = oat_dex_file->source_.GetRawFile();
2236 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2237 }
2238 Options options;
2239 options.output_to_memmap_ = true;
2240 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2241 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2242 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002243 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07002244 return false;
2245 }
2246 // Set the checksum of the new oat dex file to be the original file's checksum.
2247 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2248 return true;
2249}
2250
David Brazdil7b49e6c2016-09-01 11:06:18 +01002251bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002252 File* file,
2253 OatDexFile* oat_dex_file,
2254 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002255 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2256 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002257
2258 // Extract the dex file and get the extracted size.
2259 std::string error_msg;
2260 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2261 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2262 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2263 return false;
2264 }
2265 if (file->Flush() != 0) {
2266 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2267 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2268 return false;
2269 }
2270 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2271 if (extracted_end == static_cast<off_t>(-1)) {
2272 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2273 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2274 return false;
2275 }
2276 if (extracted_end < static_cast<off_t>(start_offset)) {
2277 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2278 << " Start: " << start_offset
2279 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2280 return false;
2281 }
2282 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2283 if (extracted_size < sizeof(DexFile::Header)) {
2284 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2285 << extracted_size << " File: " << oat_dex_file->GetLocation();
2286 return false;
2287 }
2288
2289 // Read the dex file header and extract required data to OatDexFile.
2290 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2291 if (actual_offset != static_cast<off_t>(start_offset)) {
2292 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2293 << " Expected: " << start_offset
2294 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2295 return false;
2296 }
2297 if (!ReadDexFileHeader(file, oat_dex_file)) {
2298 return false;
2299 }
2300 if (extracted_size < oat_dex_file->dex_file_size_) {
2301 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2302 << " file size from header: " << oat_dex_file->dex_file_size_
2303 << " File: " << oat_dex_file->GetLocation();
2304 return false;
2305 }
2306
2307 // Override the checksum from header with the CRC from ZIP entry.
2308 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2309
2310 // Seek both file and stream to the end offset.
2311 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2312 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2313 if (actual_offset != static_cast<off_t>(end_offset)) {
2314 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2315 << " Expected: " << end_offset
2316 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2317 return false;
2318 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002319 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002320 if (actual_offset != static_cast<off_t>(end_offset)) {
2321 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2322 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2323 return false;
2324 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002325 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002326 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2327 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2328 return false;
2329 }
2330
2331 // If we extracted more than the size specified in the header, truncate the file.
2332 if (extracted_size > oat_dex_file->dex_file_size_) {
2333 if (file->SetLength(end_offset) != 0) {
2334 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002335 << " File: " << oat_dex_file->GetLocation()
2336 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002337 return false;
2338 }
2339 }
2340
2341 return true;
2342}
2343
David Brazdil7b49e6c2016-09-01 11:06:18 +01002344bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002345 File* file,
2346 OatDexFile* oat_dex_file,
2347 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002348 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2349 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002350
2351 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2352 if (input_offset != static_cast<off_t>(0)) {
2353 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2354 << " Expected: 0"
2355 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2356 return false;
2357 }
2358 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2359 return false;
2360 }
2361
2362 // Copy the input dex file using sendfile().
2363 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2364 PLOG(ERROR) << "Failed to copy dex file to oat file."
2365 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2366 return false;
2367 }
2368 if (file->Flush() != 0) {
2369 PLOG(ERROR) << "Failed to flush dex file."
2370 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2371 return false;
2372 }
2373
2374 // Check file position and seek the stream to the end offset.
2375 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2376 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2377 if (actual_offset != static_cast<off_t>(end_offset)) {
2378 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2379 << " Expected: " << end_offset
2380 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2381 return false;
2382 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002383 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002384 if (actual_offset != static_cast<off_t>(end_offset)) {
2385 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2386 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2387 return false;
2388 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002389 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002390 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2391 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2392 return false;
2393 }
2394
2395 return true;
2396}
2397
David Brazdil7b49e6c2016-09-01 11:06:18 +01002398bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002399 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002400 const uint8_t* dex_file,
2401 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002402 // Note: The raw data has already been checked to contain the header
2403 // and all the data that the header specifies as the file size.
2404 DCHECK(dex_file != nullptr);
2405 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2406 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2407
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00002408 if (update_input_vdex) {
2409 // The vdex already contains the dex code, no need to write it again.
2410 } else {
2411 if (!out->WriteFully(dex_file, header->file_size_)) {
2412 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2413 << " to " << out->GetLocation();
2414 return false;
2415 }
2416 if (!out->Flush()) {
2417 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2418 << " File: " << oat_dex_file->GetLocation();
2419 return false;
2420 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002421 }
2422
2423 // Update dex file size and resize class offsets in the OatDexFile.
2424 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002425 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002426 oat_dex_file->dex_file_size_ = header->file_size_;
2427 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2428 return true;
2429}
2430
2431bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2432 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2433
David Brazdil181e1cc2016-09-01 16:38:47 +00002434 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2435 if (initial_offset == static_cast<off_t>(-1)) {
2436 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2437 return false;
2438 }
2439
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002440 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2441 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2442 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2443 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2444 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2445 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2446 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2447 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2448 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2449 return false;
2450 }
2451
2452 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2453 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2454
2455 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2456 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2457
2458 // Write OatDexFile.
2459 if (!oat_dex_file->Write(this, rodata)) {
2460 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2461 return false;
2462 }
2463 }
2464
David Brazdil181e1cc2016-09-01 16:38:47 +00002465 // Seek back to the initial position.
2466 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2467 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2468 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2469 return false;
2470 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002471
David Brazdilb92ba622016-09-01 16:00:30 +00002472 return true;
2473}
2474
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002475bool OatWriter::OpenDexFiles(
2476 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002477 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002478 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2479 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2480 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2481
2482 if (oat_dex_files_.empty()) {
2483 // Nothing to do.
2484 return true;
2485 }
2486
2487 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002488 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2489
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002490 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002491 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2492 length,
2493 PROT_READ | PROT_WRITE,
2494 MAP_SHARED,
2495 file->Fd(),
2496 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2497 /* low_4gb */ false,
2498 file->GetPath().c_str(),
2499 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002500 if (dex_files_map == nullptr) {
2501 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2502 << " error: " << error_msg;
2503 return false;
2504 }
2505 std::vector<std::unique_ptr<const DexFile>> dex_files;
2506 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2507 // Make sure no one messed with input files while we were copying data.
2508 // At the very least we need consistent file size and number of class definitions.
2509 const uint8_t* raw_dex_file =
2510 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2511 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2512 // Note: ValidateDexFileHeader() already logged an error message.
2513 LOG(ERROR) << "Failed to verify written dex file header!"
2514 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2515 << " ~ " << static_cast<const void*>(raw_dex_file);
2516 return false;
2517 }
2518 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2519 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2520 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2521 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2522 << " Output: " << file->GetPath();
2523 return false;
2524 }
2525 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2526 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2527 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2528 << " Output: " << file->GetPath();
2529 return false;
2530 }
2531
2532 // Now, open the dex file.
2533 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2534 oat_dex_file.dex_file_size_,
2535 oat_dex_file.GetLocation(),
2536 oat_dex_file.dex_file_location_checksum_,
2537 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002538 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002539 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002540 &error_msg));
2541 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002542 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2543 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002544 return false;
2545 }
2546 }
2547
2548 *opened_dex_files_map = std::move(dex_files_map);
2549 *opened_dex_files = std::move(dex_files);
2550 return true;
2551}
2552
2553bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002554 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002555 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2556 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2557
David Brazdil7b49e6c2016-09-01 11:06:18 +01002558 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2559 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2560 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2561 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2562 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2563 return false;
2564 }
2565
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002566 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2567 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2568 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002569 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2570
2571 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2572 oat_dex_file->class_offsets_.empty()) {
2573 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002574 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002575
2576 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2577 if (table_size == 0u) {
2578 continue;
2579 }
2580
2581 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002582 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002583 const DexFile& dex_file = *opened_dex_files[i];
2584 {
2585 std::unique_ptr<TypeLookupTable> type_lookup_table =
2586 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2587 type_lookup_table_oat_dex_files_.push_back(
2588 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2589 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2590 }
2591 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002592
2593 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002594 size_t initial_offset = oat_size_;
2595 size_t rodata_offset = RoundUp(initial_offset, 4);
2596 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002597
2598 if (padding_size != 0u) {
2599 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002600 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002601 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2602 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002603 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002604 return false;
2605 }
2606 }
2607
2608 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002609 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002610 DCHECK_EQ(table_size, table->RawDataLength());
2611
David Brazdil7b49e6c2016-09-01 11:06:18 +01002612 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002613 PLOG(ERROR) << "Failed to write lookup table."
2614 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002615 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002616 return false;
2617 }
2618
2619 oat_dex_file->lookup_table_offset_ = rodata_offset;
2620
David Brazdil7b49e6c2016-09-01 11:06:18 +01002621 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002622 size_oat_lookup_table_ += table_size;
2623 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002624 }
2625
David Brazdil7b49e6c2016-09-01 11:06:18 +01002626 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002627 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002628 << " File: " << oat_rodata->GetLocation();
2629 return false;
2630 }
2631
2632 return true;
2633}
2634
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002635bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002636 if (!kIsVdexEnabled) {
2637 return true;
2638 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002639 // Write checksums
2640 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2641 if (actual_offset != sizeof(VdexFile::Header)) {
2642 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2643 << " File: " << vdex_out->GetLocation();
2644 return false;
2645 }
2646
2647 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2648 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2649 if (!vdex_out->WriteFully(
2650 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2651 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2652 << vdex_out->GetLocation();
2653 return false;
2654 }
2655 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2656 }
2657
2658 // Write header.
2659 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002660 if (actual_offset != 0) {
2661 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2662 << " File: " << vdex_out->GetLocation();
2663 return false;
2664 }
2665
David Brazdil5d5a36b2016-09-14 15:34:10 +01002666 DCHECK_NE(vdex_dex_files_offset_, 0u);
2667 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2668
2669 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002670 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2671 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002672
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002673 VdexFile::Header vdex_header(oat_dex_files_.size(),
2674 dex_section_size,
2675 verifier_deps_section_size,
2676 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002677 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2678 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002679 return false;
2680 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002681 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002682
David Brazdil5d5a36b2016-09-14 15:34:10 +01002683 if (!vdex_out->Flush()) {
2684 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2685 << " File: " << vdex_out->GetLocation();
2686 return false;
2687 }
2688
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002689 return true;
2690}
2691
Vladimir Markof4da6752014-08-01 19:04:18 +01002692bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2693 static const uint8_t kPadding[] = {
2694 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2695 };
2696 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002697 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002698 return false;
2699 }
2700 size_code_alignment_ += aligned_code_delta;
2701 return true;
2702}
2703
Vladimir Marko944da602016-02-19 12:27:55 +00002704void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2705 DCHECK(dex_files_ != nullptr);
2706 DCHECK(relative_patcher_ != nullptr);
2707 DCHECK_NE(oat_data_offset_, 0u);
2708 if (image_writer_ != nullptr && !dex_files_->empty()) {
2709 // The oat data begin may not be initialized yet but the oat file offset is ready.
2710 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2711 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2712 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002713 }
2714}
2715
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002716OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2717 DexFileSource source,
2718 CreateTypeLookupTable create_type_lookup_table)
2719 : source_(source),
2720 create_type_lookup_table_(create_type_lookup_table),
2721 dex_file_size_(0),
2722 offset_(0),
2723 dex_file_location_size_(strlen(dex_file_location)),
2724 dex_file_location_data_(dex_file_location),
2725 dex_file_location_checksum_(0u),
2726 dex_file_offset_(0u),
2727 class_offsets_offset_(0u),
2728 lookup_table_offset_(0u),
2729 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002730}
2731
2732size_t OatWriter::OatDexFile::SizeOf() const {
2733 return sizeof(dex_file_location_size_)
2734 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002735 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002736 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002737 + sizeof(class_offsets_offset_)
2738 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002739}
2740
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002741void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2742 DCHECK_EQ(class_offsets_offset_, 0u);
2743 if (!class_offsets_.empty()) {
2744 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002745 size_t initial_offset = oat_writer->oat_size_;
2746 size_t offset = RoundUp(initial_offset, 4);
2747 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002748 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002749 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002750 }
2751}
2752
2753bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2754 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002755 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002756
Vladimir Markoe079e212016-05-25 12:49:49 +01002757 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002758 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002759 return false;
2760 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002761 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002762
Vladimir Markoe079e212016-05-25 12:49:49 +01002763 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002764 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002765 return false;
2766 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002767 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002768
Vladimir Markoe079e212016-05-25 12:49:49 +01002769 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002770 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002771 return false;
2772 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002773 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002774
Vladimir Markoe079e212016-05-25 12:49:49 +01002775 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002776 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002777 return false;
2778 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002779 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002780
Vladimir Markoe079e212016-05-25 12:49:49 +01002781 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002782 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2783 return false;
2784 }
2785 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2786
Vladimir Markoe079e212016-05-25 12:49:49 +01002787 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002788 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2789 return false;
2790 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002791 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002792
2793 return true;
2794}
2795
2796bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002797 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002798 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2799 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002800 return false;
2801 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002802 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002803 return true;
2804}
2805
Brian Carlstromba150c32013-08-27 17:31:03 -07002806OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002807 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002808 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002809 mirror::Class::Status status)
2810 : compiled_methods_(compiled_methods) {
2811 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002812 CHECK_LE(num_non_null_compiled_methods, num_methods);
2813
Brian Carlstrom265091e2013-01-30 14:08:26 -08002814 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002815 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2816
2817 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2818 // apply when there are 0 methods, we just arbitrarily say that 0
2819 // methods means kOatClassNoneCompiled and that we won't use
2820 // kOatClassAllCompiled unless there is at least one compiled
2821 // method. This means in an interpretter only system, we can assert
2822 // that all classes are kOatClassNoneCompiled.
2823 if (num_non_null_compiled_methods == 0) {
2824 type_ = kOatClassNoneCompiled;
2825 } else if (num_non_null_compiled_methods == num_methods) {
2826 type_ = kOatClassAllCompiled;
2827 } else {
2828 type_ = kOatClassSomeCompiled;
2829 }
2830
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002831 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002832 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002833 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002834
2835 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2836 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002837 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002838 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2839 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2840 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2841 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002842 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002843 method_bitmap_size_ = 0;
2844 }
2845
2846 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002847 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002848 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002849 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2850 } else {
2851 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2852 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2853 if (type_ == kOatClassSomeCompiled) {
2854 method_bitmap_->SetBit(i);
2855 }
2856 }
2857 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002858}
2859
Brian Carlstrom265091e2013-01-30 14:08:26 -08002860size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2861 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002862 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2863 if (method_offset == 0) {
2864 return 0;
2865 }
2866 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002867}
2868
2869size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2870 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002871 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002872}
2873
2874size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002875 return sizeof(status_)
2876 + sizeof(type_)
2877 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2878 + method_bitmap_size_
2879 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002880}
2881
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002882bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002883 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002884 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002885 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002886 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002887 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002888 return false;
2889 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002890 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002891
Vladimir Markoe079e212016-05-25 12:49:49 +01002892 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002893 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002894 return false;
2895 }
2896 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002897
Brian Carlstromba150c32013-08-27 17:31:03 -07002898 if (method_bitmap_size_ != 0) {
2899 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002900 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002901 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002902 return false;
2903 }
2904 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002905
Vladimir Markoe079e212016-05-25 12:49:49 +01002906 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002907 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002908 return false;
2909 }
2910 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2911 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002912
Vladimir Markoe079e212016-05-25 12:49:49 +01002913 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002914 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002915 return false;
2916 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002917 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002918 return true;
2919}
2920
Brian Carlstrome24fa612011-09-29 00:53:55 -07002921} // namespace art