blob: 2d4bbceb5043181e91c1680c8e5d63664f6c8678 [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,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000486 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
487 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
488 CHECK(write_state_ == WriteState::kAddingDexFileSources);
489
David Brazdil7b49e6c2016-09-01 11:06:18 +0100490 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
491 if (!RecordOatDataOffset(oat_rodata)) {
492 return false;
493 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000494
495 std::unique_ptr<MemMap> dex_files_map;
496 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100497
498 // Initialize VDEX and OAT headers.
499 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000500 // Reserve space for Vdex header and checksums.
501 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100502 }
503 size_t oat_data_offset = InitOatHeader(instruction_set,
504 instruction_set_features,
505 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
506 key_value_store);
507 oat_size_ = InitOatDexFiles(oat_data_offset);
508
509 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
510
511 if (kIsVdexEnabled) {
512 std::unique_ptr<BufferedOutputStream> vdex_out(
513 MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(vdex_file)));
514
515 // Write DEX files into VDEX, mmap and open them.
516 if (!WriteDexFiles(vdex_out.get(), vdex_file) ||
517 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
518 return false;
519 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100520 } else {
521 // Write DEX files into OAT, mmap and open them.
522 if (!WriteDexFiles(oat_rodata, vdex_file) ||
523 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
524 return false;
525 }
526
527 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
528 // difficult because we're not using the OutputStream directly.
529 if (!oat_dex_files_.empty()) {
530 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
531 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
532 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000533 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000534
David Brazdil7b49e6c2016-09-01 11:06:18 +0100535 // Write TypeLookupTables into OAT.
David Brazdil181e1cc2016-09-01 16:38:47 +0000536 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
537 return false;
538 }
539
David Brazdil7b49e6c2016-09-01 11:06:18 +0100540 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000541 for (OatDexFile& oat_dex_file : oat_dex_files_) {
542 oat_dex_file.ReserveClassOffsets(this);
543 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100544
David Brazdil7b49e6c2016-09-01 11:06:18 +0100545 // Write OatDexFiles into OAT. Needs to be done last, once offsets are collected.
David Brazdil181e1cc2016-09-01 16:38:47 +0000546 if (!WriteOatDexFiles(&checksum_updating_rodata)) {
547 return false;
David Brazdilb92ba622016-09-01 16:00:30 +0000548 }
549
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000550 *opened_dex_files_map = std::move(dex_files_map);
551 *opened_dex_files = std::move(dex_files);
552 write_state_ = WriteState::kPrepareLayout;
553 return true;
554}
555
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100556void OatWriter::PrepareLayout(linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 CHECK(write_state_ == WriteState::kPrepareLayout);
558
Vladimir Marko944da602016-02-19 12:27:55 +0000559 relative_patcher_ = relative_patcher;
560 SetMultiOatRelativePatcherAdjustment();
561
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000562 if (compiling_boot_image_) {
563 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800564 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100565 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000566 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100567
David Brazdil7b49e6c2016-09-01 11:06:18 +0100568 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800569 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000570 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800571 offset = InitOatClasses(offset);
572 }
573 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000574 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100575 offset = InitOatMaps(offset);
576 }
577 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000578 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800579 offset = InitOatCode(offset);
580 }
581 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000582 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800583 offset = InitOatCodeDexFiles(offset);
584 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100585 oat_size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700586
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800587 if (!HasBootImage()) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000588 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
589 InitBssLayout(instruction_set);
Vladimir Marko09d09432015-09-08 13:47:48 +0100590 }
591
Brian Carlstrome24fa612011-09-29 00:53:55 -0700592 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800593 if (compiling_boot_image_) {
594 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000595 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800596 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000597
598 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700599}
600
Ian Rogers0571d352011-11-03 19:51:38 -0700601OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700602}
603
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100604class OatWriter::DexMethodVisitor {
605 public:
606 DexMethodVisitor(OatWriter* writer, size_t offset)
607 : writer_(writer),
608 offset_(offset),
609 dex_file_(nullptr),
610 class_def_index_(DexFile::kDexNoIndex) {
611 }
612
613 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
614 DCHECK(dex_file_ == nullptr);
615 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
616 dex_file_ = dex_file;
617 class_def_index_ = class_def_index;
618 return true;
619 }
620
621 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
622
623 virtual bool EndClass() {
624 if (kIsDebugBuild) {
625 dex_file_ = nullptr;
626 class_def_index_ = DexFile::kDexNoIndex;
627 }
628 return true;
629 }
630
631 size_t GetOffset() const {
632 return offset_;
633 }
634
635 protected:
636 virtual ~DexMethodVisitor() { }
637
638 OatWriter* const writer_;
639
640 // The offset is usually advanced for each visited method by the derived class.
641 size_t offset_;
642
643 // The dex file and class def index are set in StartClass().
644 const DexFile* dex_file_;
645 size_t class_def_index_;
646};
647
648class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
649 public:
650 OatDexMethodVisitor(OatWriter* writer, size_t offset)
651 : DexMethodVisitor(writer, offset),
652 oat_class_index_(0u),
653 method_offsets_index_(0u) {
654 }
655
656 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
657 DexMethodVisitor::StartClass(dex_file, class_def_index);
658 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
659 method_offsets_index_ = 0u;
660 return true;
661 }
662
663 bool EndClass() {
664 ++oat_class_index_;
665 return DexMethodVisitor::EndClass();
666 }
667
668 protected:
669 size_t oat_class_index_;
670 size_t method_offsets_index_;
671};
672
673class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
674 public:
675 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
676 : DexMethodVisitor(writer, offset),
677 compiled_methods_(),
678 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000679 size_t num_classes = 0u;
680 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
681 num_classes += oat_dex_file.class_offsets_.size();
682 }
683 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100684 compiled_methods_.reserve(256u);
685 }
686
687 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
688 DexMethodVisitor::StartClass(dex_file, class_def_index);
689 compiled_methods_.clear();
690 num_non_null_compiled_methods_ = 0u;
691 return true;
692 }
693
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300694 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
695 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100696 // Fill in the compiled_methods_ array for methods that have a
697 // CompiledMethod. We track the number of non-null entries in
698 // num_non_null_compiled_methods_ since we only want to allocate
699 // OatMethodOffsets for the compiled methods.
700 uint32_t method_idx = it.GetMemberIndex();
701 CompiledMethod* compiled_method =
702 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
703 compiled_methods_.push_back(compiled_method);
704 if (compiled_method != nullptr) {
705 ++num_non_null_compiled_methods_;
706 }
707 return true;
708 }
709
710 bool EndClass() {
711 ClassReference class_ref(dex_file_, class_def_index_);
712 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
713 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700714 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100715 status = compiled_class->GetStatus();
716 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
717 status = mirror::Class::kStatusError;
718 } else {
719 status = mirror::Class::kStatusNotReady;
720 }
721
Vladimir Marko49b0f452015-12-10 13:49:19 +0000722 writer_->oat_classes_.emplace_back(offset_,
723 compiled_methods_,
724 num_non_null_compiled_methods_,
725 status);
726 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100727 return DexMethodVisitor::EndClass();
728 }
729
730 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000731 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100732 size_t num_non_null_compiled_methods_;
733};
734
735class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
736 public:
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100737 InitCodeMethodVisitor(OatWriter* writer, size_t offset, size_t quickening_info_offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100738 : OatDexMethodVisitor(writer, offset),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100739 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()),
740 current_quickening_info_offset_(quickening_info_offset) {
David Srbeckyf8980872015-05-22 17:04:47 +0100741 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100742 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
743 }
744
745 bool EndClass() {
746 OatDexMethodVisitor::EndClass();
747 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100748 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100749 }
750 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100751 }
752
753 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700754 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000755 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100756 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
757
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100758 if (it.GetMethodCodeItem() != nullptr) {
759 current_quickening_info_offset_ += sizeof(uint32_t);
760 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100761 if (compiled_method != nullptr) {
762 // Derived from CompiledMethod.
763 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100764
Vladimir Marko35831e82015-09-11 11:59:18 +0100765 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
766 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800767 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800768
David Srbecky009e2a62015-04-15 02:46:30 +0100769 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100770 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800771 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000772 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000773 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
774 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800775 // Duplicate methods, we want the same code for both of them so that the oat writer puts
776 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800777 } else {
778 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100779 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800780 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000781 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100782 quick_code_offset = dedupe_map_.GetOrCreate(
783 compiled_method,
784 [this, &deduped, compiled_method, &it, thumb_offset]() {
785 deduped = false;
786 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
787 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800788 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100789
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100790 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000791 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100792 // TODO: Should this be a hard failure?
793 LOG(WARNING) << "Multiple definitions of "
David Sehr709b0702016-10-13 09:12:37 -0700794 << method_ref.dex_file->PrettyMethod(method_ref.dex_method_index)
Vladimir Marko944da602016-02-19 12:27:55 +0000795 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
796 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100797 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000798 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100799 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800800 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100801
Elliott Hughes956af0f2014-12-11 14:34:28 -0800802 // Update quick method header.
803 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
804 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Mingyao Yang063fc772016-08-02 11:02:54 -0700805 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800806 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
807 // to 0-offset and we need to adjust it by code_offset.
808 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100809 if (!compiled_method->GetQuickCode().empty()) {
810 // If the code is compiled, we write the offset of the stack map relative
811 // to the code,
812 if (vmap_table_offset != 0u) {
813 vmap_table_offset += code_offset;
814 DCHECK_LT(vmap_table_offset, code_offset);
815 }
816 } else {
817 if (kIsVdexEnabled) {
818 // We write the offset in the .vdex file.
819 DCHECK_EQ(vmap_table_offset, 0u);
820 vmap_table_offset = current_quickening_info_offset_;
821 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
822 current_quickening_info_offset_ += map.size() * sizeof(map.front());
823 } else {
824 // We write the offset of the quickening info relative to the code.
825 vmap_table_offset += code_offset;
826 DCHECK_LT(vmap_table_offset, code_offset);
827 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800828 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800829 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
830 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
831 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100832 *method_header = OatQuickMethodHeader(vmap_table_offset,
833 frame_size_in_bytes,
834 core_spill_mask,
835 fp_spill_mask,
836 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100837
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000838 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800839 // Update offsets. (Checksum is updated when writing.)
840 offset_ += sizeof(*method_header); // Method header is prepended before code.
841 offset_ += code_size;
842 // Record absolute patch locations.
843 if (!compiled_method->GetPatches().empty()) {
844 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
845 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000846 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100847 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100848 }
Vladimir Markoaad75c62016-10-03 08:46:48 +0000849 if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
850 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
851 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
852 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100853 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100854 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800855 }
Alex Light78382fa2014-06-06 15:45:32 -0700856
David Srbecky91cc06c2016-03-07 16:13:58 +0000857 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000858 // Exclude quickened dex methods (code_size == 0) since they have no native code.
859 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
860 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800861 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000862 debug::MethodDebugInfo info = debug::MethodDebugInfo();
863 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000864 info.dex_file = dex_file_;
865 info.class_def_index = class_def_index_;
866 info.dex_method_index = it.GetMemberIndex();
867 info.access_flags = it.GetMethodAccessFlags();
868 info.code_item = it.GetMethodCodeItem();
869 info.isa = compiled_method->GetInstructionSet();
870 info.deduped = deduped;
871 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
872 info.is_optimized = method_header->IsOptimized();
873 info.is_code_address_text_relative = true;
874 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
875 info.code_size = code_size;
876 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
877 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
878 info.cfi = compiled_method->GetCFIInfo();
879 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100880 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100881
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100882 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
883 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
884 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100885 ++method_offsets_index_;
886 }
887
888 return true;
889 }
890
891 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000892 struct CodeOffsetsKeyComparator {
893 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100894 // Code is deduplicated by CompilerDriver, compare only data pointers.
895 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
896 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000897 }
898 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100899 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
900 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000901 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100902 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
903 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000904 }
905 return false;
906 }
907 };
908
David Srbecky009e2a62015-04-15 02:46:30 +0100909 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
910 const ClassDataItemIterator& it,
911 uint32_t thumb_offset) {
912 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100913 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
Vladimir Marko0c737df2016-08-01 16:33:16 +0100914 offset_ += CodeAlignmentSize(offset_, *compiled_method);
915 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +0100916 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
917 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
918 }
919
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920 // Deduplication is already done on a pointer basis by the compiler driver,
921 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100922 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100923
David Srbecky009e2a62015-04-15 02:46:30 +0100924 // Cache of compiler's --debuggable option.
925 const bool debuggable_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100926
927 // Offset in the vdex file for the quickening info.
928 uint32_t current_quickening_info_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100929};
930
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100931class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
932 public:
933 InitMapMethodVisitor(OatWriter* writer, size_t offset)
934 : OatDexMethodVisitor(writer, offset) {
935 }
936
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700937 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700938 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000939 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100940 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
941
942 if (compiled_method != nullptr) {
943 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100944 // If vdex is enabled, we only emit the stack map of compiled code. The quickening info will
945 // be in the vdex file.
946 if (!compiled_method->GetQuickCode().empty() || !kIsVdexEnabled) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700947 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100948
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100949 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
950 uint32_t map_size = map.size() * sizeof(map[0]);
951 if (map_size != 0u) {
952 size_t offset = dedupe_map_.GetOrCreate(
953 map.data(),
954 [this, map_size]() {
955 uint32_t new_offset = offset_;
956 offset_ += map_size;
957 return new_offset;
958 });
959 // Code offset is not initialized yet, so set the map offset to 0u-offset.
960 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700961 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100962 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 }
964 ++method_offsets_index_;
965 }
966
967 return true;
968 }
969
970 private:
971 // Deduplication is already done on a pointer basis by the compiler driver,
972 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100973 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100974};
975
976class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
977 public:
978 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800979 : OatDexMethodVisitor(writer, offset),
980 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100981 }
982
983 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700984 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800985 const DexFile::TypeId& type_id =
986 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
987 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
988 // Skip methods that are not in the image.
989 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
990 return true;
991 }
992
Vladimir Marko49b0f452015-12-10 13:49:19 +0000993 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100994 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
995
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800996 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100997 if (compiled_method != nullptr) {
998 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
999 offsets = oat_class->method_offsets_[method_offsets_index_];
1000 ++method_offsets_index_;
1001 }
1002
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001003 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001004 // Unchecked as we hold mutator_lock_ on entry.
1005 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001006 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001007 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
1008 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001009 ArtMethod* method;
1010 if (writer_->HasBootImage()) {
1011 const InvokeType invoke_type = it.GetMethodInvokeType(
1012 dex_file_->GetClassDef(class_def_index_));
1013 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
1014 *dex_file_,
1015 it.GetMemberIndex(),
1016 dex_cache,
1017 ScopedNullHandle<mirror::ClassLoader>(),
1018 nullptr,
1019 invoke_type);
1020 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001021 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001022 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001023 soa.Self()->AssertPendingException();
1024 mirror::Throwable* exc = soa.Self()->GetException();
1025 std::string dump = exc->Dump();
1026 LOG(FATAL) << dump;
1027 UNREACHABLE();
1028 }
1029 } else {
1030 // Should already have been resolved by the compiler, just peek into the dex cache.
1031 // It may not be resolved if the class failed to verify, in this case, don't set the
1032 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
1033 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -07001034 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001035 if (method != nullptr &&
1036 compiled_method != nullptr &&
1037 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001038 method->SetEntryPointFromQuickCompiledCodePtrSize(
1039 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1040 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001041
1042 return true;
1043 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001044
1045 protected:
Andreas Gampe542451c2016-07-26 09:02:02 -07001046 const PointerSize pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001047};
1048
1049class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1050 public:
1051 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001052 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001053 : OatDexMethodVisitor(writer, relative_offset),
1054 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001055 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001056 soa_(Thread::Current()),
Mathieu Chartier268764d2016-09-13 12:09:38 -07001057 no_thread_suspension_("OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001058 class_linker_(Runtime::Current()->GetClassLinker()),
1059 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001060 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001061 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001062 // If we're creating the image, the address space must be ready so that we can apply patches.
1063 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001064 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001065 }
1066
Vladimir Markof4da6752014-08-01 19:04:18 +01001067 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001068 }
1069
1070 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001071 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001072 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1073 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001074 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001075 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001076 }
1077 return true;
1078 }
1079
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001080 bool EndClass() REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001081 bool result = OatDexMethodVisitor::EndClass();
1082 if (oat_class_index_ == writer_->oat_classes_.size()) {
1083 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001084 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001085 if (UNLIKELY(offset_ == 0u)) {
1086 PLOG(ERROR) << "Failed to write final relative call thunks";
1087 result = false;
1088 }
1089 }
1090 return result;
1091 }
1092
1093 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001094 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001095 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001096 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1097
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001098 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001099 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001100 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001101 size_t file_offset = file_offset_;
1102 OutputStream* out = out_;
1103
Vladimir Marko35831e82015-09-11 11:59:18 +01001104 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1105 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001106
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001107 // Deduplicate code arrays.
1108 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1109 if (method_offsets.code_offset_ > offset_) {
1110 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1111 if (offset_ == 0u) {
1112 ReportWriteFailure("relative call thunk", it);
1113 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001114 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001115 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1116 if (alignment_size != 0) {
1117 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001118 ReportWriteFailure("code alignment padding", it);
1119 return false;
1120 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001121 offset_ += alignment_size;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001122 DCHECK_OFFSET_();
1123 }
Vladimir Marko0c737df2016-08-01 16:33:16 +01001124 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001125 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1126 DCHECK_EQ(method_offsets.code_offset_,
1127 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
David Sehr709b0702016-10-13 09:12:37 -07001128 << dex_file_->PrettyMethod(it.GetMemberIndex());
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001129 const OatQuickMethodHeader& method_header =
1130 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001131 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001132 ReportWriteFailure("method header", it);
1133 return false;
1134 }
1135 writer_->size_method_header_ += sizeof(method_header);
1136 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001137 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001138
1139 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001140 patched_code_.assign(quick_code.begin(), quick_code.end());
1141 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001142 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001143 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001144 switch (patch.GetType()) {
1145 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001146 // NOTE: Relative calls across oat files are not supported.
1147 uint32_t target_offset = GetTargetOffset(patch);
1148 writer_->relative_patcher_->PatchCall(&patched_code_,
1149 literal_offset,
1150 offset_ + literal_offset,
1151 target_offset);
1152 break;
1153 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001154 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001155 uint32_t target_offset = GetDexCacheOffset(patch);
1156 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1157 patch,
1158 offset_ + literal_offset,
1159 target_offset);
1160 break;
1161 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001162 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001163 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1164 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1165 patch,
1166 offset_ + literal_offset,
1167 target_offset);
1168 break;
1169 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001170 case LinkerPatch::Type::kStringBssEntry: {
1171 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1172 uint32_t target_offset = writer_->bss_string_entries_.Get(ref);
1173 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1174 patch,
1175 offset_ + literal_offset,
1176 target_offset);
1177 break;
1178 }
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001179 case LinkerPatch::Type::kTypeRelative: {
1180 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1181 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1182 patch,
1183 offset_ + literal_offset,
1184 target_offset);
1185 break;
1186 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001187 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001188 uint32_t target_offset = GetTargetOffset(patch);
1189 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1190 break;
1191 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001192 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001193 ArtMethod* method = GetTargetMethod(patch);
1194 PatchMethodAddress(&patched_code_, literal_offset, method);
1195 break;
1196 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001197 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001198 mirror::String* string = GetTargetString(patch);
1199 PatchObjectAddress(&patched_code_, literal_offset, string);
1200 break;
1201 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001202 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001203 mirror::Class* type = GetTargetType(patch);
1204 PatchObjectAddress(&patched_code_, literal_offset, type);
1205 break;
1206 }
1207 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001208 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001209 break;
1210 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001211 }
1212 }
1213 }
1214
Vladimir Markoe079e212016-05-25 12:49:49 +01001215 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001216 ReportWriteFailure("method code", it);
1217 return false;
1218 }
1219 writer_->size_code_ += code_size;
1220 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001221 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001222 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001223 ++method_offsets_index_;
1224 }
1225
1226 return true;
1227 }
1228
1229 private:
1230 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001231 const size_t file_offset_;
1232 const ScopedObjectAccess soa_;
1233 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001234 ClassLinker* const class_linker_;
1235 mirror::DexCache* dex_cache_;
1236 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001237
1238 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1239 PLOG(ERROR) << "Failed to write " << what << " for "
David Sehr709b0702016-10-13 09:12:37 -07001240 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001241 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001242
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001244 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001245 MethodReference ref = patch.TargetMethod();
1246 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001247 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1248 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001249 ArtMethod* method = dex_cache->GetResolvedMethod(
1250 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001251 CHECK(method != nullptr);
1252 return method;
1253 }
1254
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001255 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001256 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1257 // If there's no new compiled code, either we're compiling an app and the target method
1258 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001259 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001260 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001261 DCHECK(target != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001262 PointerSize size =
1263 GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001264 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1265 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001266 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001267 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1268 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1269 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1270 target_offset = PointerToLowMemUInt32(oat_code_offset);
1271 } else {
1272 target_offset = target->IsNative()
1273 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1274 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1275 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001276 }
1277 return target_offset;
1278 }
1279
Vladimir Marko052164a2016-04-27 13:54:18 +01001280 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001281 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001282 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001283 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001284 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1285 }
1286
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001287 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001288 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001289 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1290 CHECK(type != nullptr);
1291 return type;
1292 }
1293
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001294 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001295 ScopedObjectAccessUnchecked soa(Thread::Current());
1296 StackHandleScope<1> hs(soa.Self());
1297 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1298 Handle<mirror::DexCache> dex_cache(hs.NewHandle(GetDexCache(patch.TargetStringDexFile())));
1299 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1300 patch.TargetStringIndex(),
1301 dex_cache);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001302 DCHECK(string != nullptr);
1303 DCHECK(writer_->HasBootImage() ||
1304 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1305 return string;
1306 }
1307
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001308 uint32_t GetDexCacheOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001309 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001310 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1311 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1312 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1313 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001314 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001315 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001316 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1317 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001318 }
1319 }
1320
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001321 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001322 DCHECK(writer_->HasBootImage());
1323 object = writer_->image_writer_->GetImageAddress(object);
1324 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1325 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1326 // TODO: Clean up offset types. The target offset must be treated as signed.
1327 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1328 }
1329
Vladimir Markof4da6752014-08-01 19:04:18 +01001330 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001331 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001332 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001333 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001334 } else {
1335 // NOTE: We're using linker patches for app->boot references when the image can
1336 // be relocated and therefore we need to emit .oat_patches. We're not using this
1337 // for app->app references, so check that the object is in the image space.
1338 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001339 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001340 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001341 uint32_t address = PointerToLowMemUInt32(object);
1342 DCHECK_LE(offset + 4, code->size());
1343 uint8_t* data = &(*code)[offset];
1344 data[0] = address & 0xffu;
1345 data[1] = (address >> 8) & 0xffu;
1346 data[2] = (address >> 16) & 0xffu;
1347 data[3] = (address >> 24) & 0xffu;
1348 }
1349
Mathieu Chartiere401d142015-04-22 13:56:20 -07001350 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001351 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001352 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001353 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001354 } else if (kIsDebugBuild) {
1355 // NOTE: We're using linker patches for app->boot references when the image can
1356 // be relocated and therefore we need to emit .oat_patches. We're not using this
1357 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001358 std::vector<gc::space::ImageSpace*> image_spaces =
1359 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1360 bool contains_method = false;
1361 for (gc::space::ImageSpace* image_space : image_spaces) {
1362 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1363 contains_method |=
1364 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1365 }
1366 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001367 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001368 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001369 uint32_t address = PointerToLowMemUInt32(method);
1370 DCHECK_LE(offset + 4, code->size());
1371 uint8_t* data = &(*code)[offset];
1372 data[0] = address & 0xffu;
1373 data[1] = (address >> 8) & 0xffu;
1374 data[2] = (address >> 16) & 0xffu;
1375 data[3] = (address >> 24) & 0xffu;
1376 }
1377
Vladimir Markof4da6752014-08-01 19:04:18 +01001378 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001379 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001380 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001381 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001382 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1383 // TODO: Clean up offset types.
1384 // The target_offset must be treated as signed for cross-oat patching.
1385 const void* target = reinterpret_cast<const void*>(
1386 writer_->image_writer_->GetOatDataBegin(oat_index) +
1387 static_cast<int32_t>(target_offset));
1388 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001389 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001390 DCHECK_LE(offset + 4, code->size());
1391 uint8_t* data = &(*code)[offset];
1392 data[0] = address & 0xffu;
1393 data[1] = (address >> 8) & 0xffu;
1394 data[2] = (address >> 16) & 0xffu;
1395 data[3] = (address >> 24) & 0xffu;
1396 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001397};
1398
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001399class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1400 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001401 WriteMapMethodVisitor(OatWriter* writer,
1402 OutputStream* out,
1403 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001404 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001405 : OatDexMethodVisitor(writer, relative_offset),
1406 out_(out),
1407 file_offset_(file_offset) {
1408 }
1409
1410 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001411 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001412 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1413
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001414 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001415 size_t file_offset = file_offset_;
1416 OutputStream* out = out_;
1417
Mingyao Yang063fc772016-08-02 11:02:54 -07001418 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001419 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001420 ++method_offsets_index_;
1421
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001422 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1423 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1424 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07001425 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001426
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001427 // If vdex is enabled, only emit the map for compiled code. The quickening info
1428 // is emitted in the vdex already.
1429 if (map_offset != 0u &&
1430 !(kIsVdexEnabled && compiled_method->GetQuickCode().empty())) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001431 // Transform map_offset to actual oat data offset.
1432 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1433 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07001434 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001435
1436 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1437 size_t map_size = map.size() * sizeof(map[0]);
1438 if (map_offset == offset_) {
1439 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001440 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001441 ReportWriteFailure(it);
1442 return false;
1443 }
1444 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001445 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001446 }
1447 DCHECK_OFFSET_();
1448 }
1449
1450 return true;
1451 }
1452
1453 private:
1454 OutputStream* const out_;
1455 size_t const file_offset_;
1456
1457 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001458 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07001459 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001460 }
1461};
1462
1463// Visit all methods from all classes in all dex files with the specified visitor.
1464bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1465 for (const DexFile* dex_file : *dex_files_) {
1466 const size_t class_def_count = dex_file->NumClassDefs();
1467 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1468 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1469 return false;
1470 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001471 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1472 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1473 const uint8_t* class_data = dex_file->GetClassData(class_def);
1474 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
1475 ClassDataItemIterator it(*dex_file, class_data);
1476 while (it.HasNextStaticField()) {
1477 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001478 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001479 while (it.HasNextInstanceField()) {
1480 it.Next();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001481 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001482 size_t class_def_method_index = 0u;
1483 while (it.HasNextDirectMethod()) {
1484 if (!visitor->VisitMethod(class_def_method_index, it)) {
1485 return false;
1486 }
1487 ++class_def_method_index;
1488 it.Next();
1489 }
1490 while (it.HasNextVirtualMethod()) {
1491 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1492 return false;
1493 }
1494 ++class_def_method_index;
1495 it.Next();
1496 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001497 }
1498 }
1499 if (UNLIKELY(!visitor->EndClass())) {
1500 return false;
1501 }
1502 }
1503 }
1504 return true;
1505}
1506
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001507size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1508 const InstructionSetFeatures* instruction_set_features,
1509 uint32_t num_dex_files,
1510 SafeMap<std::string, std::string>* key_value_store) {
1511 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1512 oat_header_.reset(OatHeader::Create(instruction_set,
1513 instruction_set_features,
1514 num_dex_files,
1515 key_value_store));
1516 size_oat_header_ += sizeof(OatHeader);
1517 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001518 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001519}
1520
1521size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001522 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1523 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001524 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001525 oat_dex_file.offset_ = offset;
1526 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001527 }
1528 return offset;
1529}
1530
Brian Carlstrom389efb02012-01-11 12:06:26 -08001531size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001532 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001533 InitOatClassesMethodVisitor visitor(this, offset);
1534 bool success = VisitDexMethods(&visitor);
1535 CHECK(success);
1536 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001537
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001538 // Update oat_dex_files_.
1539 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001540 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1541 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001542 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001543 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001544 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001545 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001546 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001547 CHECK(oat_class_it == oat_classes_.end());
1548
1549 return offset;
1550}
1551
1552size_t OatWriter::InitOatMaps(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001553 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1554 return offset;
1555 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001556 InitMapMethodVisitor visitor(this, offset);
1557 bool success = VisitDexMethods(&visitor);
1558 DCHECK(success);
1559 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001560
Brian Carlstrome24fa612011-09-29 00:53:55 -07001561 return offset;
1562}
1563
1564size_t OatWriter::InitOatCode(size_t offset) {
1565 // calculate the offsets within OatHeader to executable code
1566 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001567 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001568 // required to be on a new page boundary
1569 offset = RoundUp(offset, kPageSize);
1570 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001571 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Markoaad75c62016-10-03 08:46:48 +00001572 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001573 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001574
Ian Rogers848871b2013-08-05 10:56:33 -07001575 #define DO_TRAMPOLINE(field, fn_name) \
1576 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001577 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1578 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001579 (field) = compiler_driver_->Create ## fn_name(); \
1580 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001581
Ian Rogers848871b2013-08-05 10:56:33 -07001582 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001583 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001584 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001585 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1586 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001587
Ian Rogers848871b2013-08-05 10:56:33 -07001588 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001589 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001590 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1591 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1592 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001593 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001594 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001595 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001596 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001597 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001598 return offset;
1599}
1600
1601size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001602 if (!compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1603 return offset;
1604 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001605 InitCodeMethodVisitor code_visitor(this, offset, vdex_quickening_info_offset_);
1606 bool success = VisitDexMethods(&code_visitor);
1607 DCHECK(success);
1608 offset = code_visitor.GetOffset();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001609
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001610 if (HasImage()) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001611 InitImageMethodVisitor image_visitor(this, offset);
1612 success = VisitDexMethods(&image_visitor);
1613 DCHECK(success);
1614 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07001615 }
Logan Chien8b977d32012-02-21 19:14:55 +08001616
Brian Carlstrome24fa612011-09-29 00:53:55 -07001617 return offset;
1618}
1619
Vladimir Markoaad75c62016-10-03 08:46:48 +00001620void OatWriter::InitBssLayout(InstructionSet instruction_set) {
1621 DCHECK(!HasBootImage());
1622
1623 // Allocate space for app dex cache arrays in the .bss section.
1624 bss_start_ = RoundUp(oat_size_, kPageSize);
1625 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
1626 bss_size_ = 0u;
1627 for (const DexFile* dex_file : *dex_files_) {
1628 dex_cache_arrays_offsets_.Put(dex_file, bss_start_ + bss_size_);
1629 DexCacheArraysLayout layout(pointer_size, dex_file);
1630 bss_size_ += layout.Size();
1631 }
1632
1633 bss_roots_offset_ = bss_size_;
1634
1635 // Prepare offsets for .bss String entries.
1636 for (auto& entry : bss_string_entries_) {
1637 DCHECK_EQ(entry.second, 0u);
1638 entry.second = bss_start_ + bss_size_;
1639 bss_size_ += sizeof(GcRoot<mirror::String>);
1640 }
1641}
1642
David Srbeckybc90fd02015-04-22 19:40:27 +01001643bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001644 CHECK(write_state_ == WriteState::kWriteRoData);
1645
Vladimir Markoe079e212016-05-25 12:49:49 +01001646 // Wrap out to update checksum with each write.
1647 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1648 out = &checksum_updating_out;
1649
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001650 if (!WriteClassOffsets(out)) {
1651 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001652 return false;
1653 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001654
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001655 if (!WriteClasses(out)) {
1656 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001657 return false;
1658 }
1659
Vladimir Markof4da6752014-08-01 19:04:18 +01001660 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001661 if (tables_end_offset == static_cast<off_t>(-1)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00001662 LOG(ERROR) << "Failed to get oat code position in " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001663 return false;
1664 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001665 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001666 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001667 relative_offset = WriteMaps(out, file_offset, relative_offset);
1668 if (relative_offset == 0) {
1669 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1670 return false;
1671 }
1672
David Srbeckybc90fd02015-04-22 19:40:27 +01001673 // Write padding.
1674 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1675 relative_offset += size_executable_offset_alignment_;
1676 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1677 size_t expected_file_offset = file_offset + relative_offset;
1678 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1679 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1680 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1681 return 0;
1682 }
1683 DCHECK_OFFSET();
1684
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001686 return true;
1687}
1688
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001689class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
1690 public:
1691 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out, uint32_t offset)
1692 : DexMethodVisitor(writer, offset),
1693 out_(out),
1694 written_bytes_(0u) {}
1695
1696 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
1697 const ClassDataItemIterator& it) {
1698 if (it.GetMethodCodeItem() == nullptr) {
1699 // No CodeItem. Native or abstract method.
1700 return true;
1701 }
1702
1703 uint32_t method_idx = it.GetMemberIndex();
1704 CompiledMethod* compiled_method =
1705 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
1706
1707 uint32_t length = 0;
1708 const uint8_t* data = nullptr;
1709 // VMap only contains quickening info if this method is not compiled.
1710 if (compiled_method != nullptr && compiled_method->GetQuickCode().empty()) {
1711 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1712 data = map.data();
1713 length = map.size() * sizeof(map.front());
1714 }
1715
1716 if (!out_->WriteFully(&length, sizeof(length)) ||
1717 !out_->WriteFully(data, length)) {
1718 PLOG(ERROR) << "Failed to write quickening info for "
1719 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
1720 return false;
1721 }
1722 offset_ += sizeof(length) + length;
1723 written_bytes_ += sizeof(length) + length;
1724 return true;
1725 }
1726
1727 size_t GetNumberOfWrittenBytes() const {
1728 return written_bytes_;
1729 }
1730
1731 private:
1732 OutputStream* const out_;
1733 size_t written_bytes_;
1734};
1735
1736bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
1737 if (!kIsVdexEnabled) {
1738 return true;
1739 }
1740
1741 size_t initial_offset = vdex_size_;
1742 size_t start_offset = RoundUp(initial_offset, 4u);
1743
1744 vdex_size_ = start_offset;
1745 vdex_quickening_info_offset_ = vdex_size_;
1746 size_quickening_info_alignment_ = start_offset - initial_offset;
1747
1748 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1749 if (actual_offset != static_cast<off_t>(start_offset)) {
1750 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
1751 << " Expected: " << start_offset
1752 << " Output: " << vdex_out->GetLocation();
1753 return false;
1754 }
1755
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001756 if (compiler_driver_->GetCompilerOptions().IsAnyMethodCompilationEnabled()) {
1757 WriteQuickeningInfoMethodVisitor visitor(this, vdex_out, start_offset);
1758 if (!VisitDexMethods(&visitor)) {
1759 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
1760 return false;
1761 }
1762
1763 if (!vdex_out->Flush()) {
1764 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
1765 << " File: " << vdex_out->GetLocation();
1766 return false;
1767 }
1768 size_quickening_info_ = visitor.GetNumberOfWrittenBytes();
1769 } else {
1770 // We know we did not quicken.
1771 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001772 }
1773
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001774 vdex_size_ += size_quickening_info_;
1775 return true;
1776}
1777
David Brazdil5d5a36b2016-09-14 15:34:10 +01001778bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
1779 if (!kIsVdexEnabled) {
1780 return true;
1781 }
1782
1783 if (verifier_deps == nullptr) {
1784 // Nothing to write. Record the offset, but no need
1785 // for alignment.
1786 vdex_verifier_deps_offset_ = vdex_size_;
1787 return true;
1788 }
1789
1790 size_t initial_offset = vdex_size_;
1791 size_t start_offset = RoundUp(initial_offset, 4u);
1792
1793 vdex_size_ = start_offset;
1794 vdex_verifier_deps_offset_ = vdex_size_;
1795 size_verifier_deps_alignment_ = start_offset - initial_offset;
1796
1797 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
1798 if (actual_offset != static_cast<off_t>(start_offset)) {
1799 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
1800 << " Expected: " << start_offset
1801 << " Output: " << vdex_out->GetLocation();
1802 return false;
1803 }
1804
1805 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01001806 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001807
1808 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
1809 PLOG(ERROR) << "Failed to write verifier deps."
1810 << " File: " << vdex_out->GetLocation();
1811 return false;
1812 }
1813 if (!vdex_out->Flush()) {
1814 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
1815 << " File: " << vdex_out->GetLocation();
1816 return false;
1817 }
1818
1819 size_verifier_deps_ = buffer.size();
1820 vdex_size_ += size_verifier_deps_;
1821 return true;
1822}
1823
David Srbeckybc90fd02015-04-22 19:40:27 +01001824bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001825 CHECK(write_state_ == WriteState::kWriteText);
1826
Vladimir Markoe079e212016-05-25 12:49:49 +01001827 // Wrap out to update checksum with each write.
1828 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1829 out = &checksum_updating_out;
1830
Vladimir Marko944da602016-02-19 12:27:55 +00001831 SetMultiOatRelativePatcherAdjustment();
1832
David Srbeckybc90fd02015-04-22 19:40:27 +01001833 const size_t file_offset = oat_data_offset_;
1834 size_t relative_offset = oat_header_->GetExecutableOffset();
1835 DCHECK_OFFSET();
1836
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001837 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001838 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001839 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001840 return false;
1841 }
1842
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001843 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1844 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001845 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001846 return false;
1847 }
1848
Vladimir Markof4da6752014-08-01 19:04:18 +01001849 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001850 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001851 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1852 return false;
1853 }
1854
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001855 if (kIsDebugBuild) {
1856 uint32_t size_total = 0;
1857 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001858 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1859 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001860
David Brazdil7b49e6c2016-09-01 11:06:18 +01001861 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00001862 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001863 DO_STAT(size_dex_file_alignment_);
1864 DO_STAT(size_executable_offset_alignment_);
1865 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001866 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001867 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01001868 DO_STAT(size_verifier_deps_);
1869 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001870 DO_STAT(size_quickening_info_);
1871 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07001872 DO_STAT(size_interpreter_to_interpreter_bridge_);
1873 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1874 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001875 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001876 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001877 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001878 DO_STAT(size_quick_to_interpreter_bridge_);
1879 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001880 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001881 DO_STAT(size_code_);
1882 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001883 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001884 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001885 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001886 DO_STAT(size_oat_dex_file_location_size_);
1887 DO_STAT(size_oat_dex_file_location_data_);
1888 DO_STAT(size_oat_dex_file_location_checksum_);
1889 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001890 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001891 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001892 DO_STAT(size_oat_lookup_table_alignment_);
1893 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001894 DO_STAT(size_oat_class_offsets_alignment_);
1895 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001896 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001897 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001898 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001899 DO_STAT(size_oat_class_method_offsets_);
1900 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001901
David Brazdil7b49e6c2016-09-01 11:06:18 +01001902 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
1903
1904 CHECK_EQ(vdex_size_ + oat_size_, size_total);
1905 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001906 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001907
David Brazdil7b49e6c2016-09-01 11:06:18 +01001908 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
1909 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001910
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001911 write_state_ = WriteState::kWriteHeader;
1912 return true;
1913}
1914
1915bool OatWriter::WriteHeader(OutputStream* out,
1916 uint32_t image_file_location_oat_checksum,
1917 uintptr_t image_file_location_oat_begin,
1918 int32_t image_patch_delta) {
1919 CHECK(write_state_ == WriteState::kWriteHeader);
1920
1921 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1922 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001923 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001924 CHECK_EQ(image_patch_delta, 0);
1925 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1926 } else {
1927 CHECK_ALIGNED(image_patch_delta, kPageSize);
1928 oat_header_->SetImagePatchDelta(image_patch_delta);
1929 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001930 oat_header_->UpdateChecksumWithHeaderData();
1931
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001932 const size_t file_offset = oat_data_offset_;
1933
1934 off_t current_offset = out->Seek(0, kSeekCurrent);
1935 if (current_offset == static_cast<off_t>(-1)) {
1936 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1937 return false;
1938 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001939 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001940 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1941 return false;
1942 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001943 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001944
1945 // Flush all other data before writing the header.
1946 if (!out->Flush()) {
1947 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1948 return false;
1949 }
1950 // Write the header.
1951 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001952 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001953 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1954 return false;
1955 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001956 // Flush the header data.
1957 if (!out->Flush()) {
1958 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001959 return false;
1960 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001961
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001962 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1963 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1964 return false;
1965 }
1966 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1967
1968 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001969 return true;
1970}
1971
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001972bool OatWriter::WriteClassOffsets(OutputStream* out) {
1973 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1974 if (oat_dex_file.class_offsets_offset_ != 0u) {
1975 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1976 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1977 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1978 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1979 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001980 return false;
1981 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001982 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1983 return false;
1984 }
1985 }
1986 }
1987 return true;
1988}
1989
1990bool OatWriter::WriteClasses(OutputStream* out) {
1991 for (OatClass& oat_class : oat_classes_) {
1992 if (!oat_class.Write(this, out, oat_data_offset_)) {
1993 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1994 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001995 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001996 }
1997 return true;
1998}
1999
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002000size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002001 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002002 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2003 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2004 return 0;
2005 }
2006 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002007 size_vmap_table_ = relative_offset - vmap_tables_offset;
2008
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002009 return relative_offset;
2010}
2011
2012size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002013 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002014 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002015
Ian Rogers848871b2013-08-05 10:56:33 -07002016 #define DO_TRAMPOLINE(field) \
2017 do { \
2018 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2019 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002020 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07002021 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01002022 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08002023 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002024 return false; \
2025 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002026 size_ ## field += (field)->size(); \
2027 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07002028 DCHECK_OFFSET(); \
2029 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002030
Ian Rogers848871b2013-08-05 10:56:33 -07002031 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002032 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002033 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002034 DO_TRAMPOLINE(quick_resolution_trampoline_);
2035 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
2036 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002037 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002038 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002039}
2040
Ian Rogers3d504072014-03-01 09:16:49 -08002041size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002042 const size_t file_offset,
2043 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002044 #define VISIT(VisitorType) \
2045 do { \
2046 VisitorType visitor(this, out, file_offset, relative_offset); \
2047 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
2048 return 0; \
2049 } \
2050 relative_offset = visitor.GetOffset(); \
2051 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07002052
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002053 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002054
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002055 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08002056
Vladimir Markob163bb72015-03-31 21:49:49 +01002057 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
2058 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
2059 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
2060
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002061 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002062}
2063
Vladimir Marko944da602016-02-19 12:27:55 +00002064bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002065 // Get the elf file offset of the oat file.
2066 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
2067 if (raw_file_offset == static_cast<off_t>(-1)) {
2068 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
2069 return false;
2070 }
2071 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
2072 return true;
2073}
2074
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002075bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
2076 // Read the dex file header and perform minimal verification.
2077 uint8_t raw_header[sizeof(DexFile::Header)];
2078 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
2079 PLOG(ERROR) << "Failed to read dex file header. Actual: "
2080 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2081 return false;
2082 }
2083 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
2084 return false;
2085 }
2086
2087 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2088 oat_dex_file->dex_file_size_ = header->file_size_;
2089 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
2090 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2091 return true;
2092}
2093
2094bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
2095 if (!DexFile::IsMagicValid(raw_header)) {
2096 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
2097 return false;
2098 }
2099 if (!DexFile::IsVersionValid(raw_header)) {
2100 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
2101 return false;
2102 }
2103 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
2104 if (header->file_size_ < sizeof(DexFile::Header)) {
2105 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
2106 << " File: " << location;
2107 return false;
2108 }
2109 return true;
2110}
2111
David Brazdil7b49e6c2016-09-01 11:06:18 +01002112bool OatWriter::WriteDexFiles(OutputStream* out, File* file) {
2113 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002114
David Brazdil7b49e6c2016-09-01 11:06:18 +01002115 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002116
2117 // Write dex files.
2118 for (OatDexFile& oat_dex_file : oat_dex_files_) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002119 if (!WriteDexFile(out, file, &oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002120 return false;
2121 }
2122 }
2123
2124 // Close sources.
2125 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2126 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
2127 }
2128 zipped_dex_files_.clear();
2129 zip_archives_.clear();
2130 raw_dex_files_.clear();
2131 return true;
2132}
2133
David Brazdil7b49e6c2016-09-01 11:06:18 +01002134bool OatWriter::WriteDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2135 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002136 return false;
2137 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07002138 if (profile_compilation_info_ != nullptr) {
2139 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
2140 return false;
2141 }
2142 } else if (oat_dex_file->source_.IsZipEntry()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002143 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002144 return false;
2145 }
2146 } else if (oat_dex_file->source_.IsRawFile()) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002147 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002148 return false;
2149 }
2150 } else {
2151 DCHECK(oat_dex_file->source_.IsRawData());
David Brazdil7b49e6c2016-09-01 11:06:18 +01002152 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002153 return false;
2154 }
2155 }
2156
2157 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002158 if (kIsVdexEnabled) {
2159 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
2160 vdex_size_ += oat_dex_file->dex_file_size_;
2161 } else {
2162 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
2163 oat_size_ += oat_dex_file->dex_file_size_;
2164 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002165 size_dex_file_ += oat_dex_file->dex_file_size_;
2166 return true;
2167}
2168
2169bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
2170 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002171 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
2172 size_t start_offset = RoundUp(initial_offset, 4);
2173 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
2174 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002175
2176 // Seek to the start of the dex file and flush any pending operations in the stream.
2177 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002178 off_t actual_offset = out->Seek(file_offset, kSeekSet);
2179 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002180 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002181 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002182 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2183 return false;
2184 }
2185 if (!out->Flush()) {
2186 PLOG(ERROR) << "Failed to flush before writing dex file."
2187 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2188 return false;
2189 }
2190 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002191 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002192 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01002193 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002194 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2195 return false;
2196 }
2197
David Brazdil7b49e6c2016-09-01 11:06:18 +01002198 if (kIsVdexEnabled) {
2199 vdex_size_ = start_offset;
2200 } else {
2201 oat_size_ = start_offset;
2202 }
2203 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002204 return true;
2205}
2206
Jeff Hao608f2ce2016-10-19 11:17:11 -07002207bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
2208 TimingLogger::ScopedTiming split("Dex Layout", timings_);
2209 std::string error_msg;
2210 std::string location(oat_dex_file->GetLocation());
2211 std::unique_ptr<const DexFile> dex_file;
2212 if (oat_dex_file->source_.IsZipEntry()) {
2213 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
2214 std::unique_ptr<MemMap> mem_map(
2215 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
2216 dex_file = DexFile::Open(location,
2217 zip_entry->GetCrc32(),
2218 std::move(mem_map),
2219 /* verify */ true,
2220 /* verify_checksum */ true,
2221 &error_msg);
2222 } else {
2223 DCHECK(oat_dex_file->source_.IsRawFile());
2224 File* raw_file = oat_dex_file->source_.GetRawFile();
2225 dex_file = DexFile::OpenDex(raw_file->Fd(), location, /* verify_checksum */ true, &error_msg);
2226 }
2227 Options options;
2228 options.output_to_memmap_ = true;
2229 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
2230 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
2231 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
2232 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin())) {
2233 return false;
2234 }
2235 // Set the checksum of the new oat dex file to be the original file's checksum.
2236 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
2237 return true;
2238}
2239
David Brazdil7b49e6c2016-09-01 11:06:18 +01002240bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002241 File* file,
2242 OatDexFile* oat_dex_file,
2243 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002244 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2245 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002246
2247 // Extract the dex file and get the extracted size.
2248 std::string error_msg;
2249 if (!dex_file->ExtractToFile(*file, &error_msg)) {
2250 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
2251 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2252 return false;
2253 }
2254 if (file->Flush() != 0) {
2255 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
2256 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2257 return false;
2258 }
2259 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
2260 if (extracted_end == static_cast<off_t>(-1)) {
2261 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
2262 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2263 return false;
2264 }
2265 if (extracted_end < static_cast<off_t>(start_offset)) {
2266 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
2267 << " Start: " << start_offset
2268 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2269 return false;
2270 }
2271 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
2272 if (extracted_size < sizeof(DexFile::Header)) {
2273 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
2274 << extracted_size << " File: " << oat_dex_file->GetLocation();
2275 return false;
2276 }
2277
2278 // Read the dex file header and extract required data to OatDexFile.
2279 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
2280 if (actual_offset != static_cast<off_t>(start_offset)) {
2281 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
2282 << " Expected: " << start_offset
2283 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2284 return false;
2285 }
2286 if (!ReadDexFileHeader(file, oat_dex_file)) {
2287 return false;
2288 }
2289 if (extracted_size < oat_dex_file->dex_file_size_) {
2290 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
2291 << " file size from header: " << oat_dex_file->dex_file_size_
2292 << " File: " << oat_dex_file->GetLocation();
2293 return false;
2294 }
2295
2296 // Override the checksum from header with the CRC from ZIP entry.
2297 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
2298
2299 // Seek both file and stream to the end offset.
2300 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2301 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
2302 if (actual_offset != static_cast<off_t>(end_offset)) {
2303 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
2304 << " Expected: " << end_offset
2305 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2306 return false;
2307 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002308 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002309 if (actual_offset != static_cast<off_t>(end_offset)) {
2310 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2311 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2312 return false;
2313 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002314 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002315 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2316 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2317 return false;
2318 }
2319
2320 // If we extracted more than the size specified in the header, truncate the file.
2321 if (extracted_size > oat_dex_file->dex_file_size_) {
2322 if (file->SetLength(end_offset) != 0) {
2323 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002324 << " File: " << oat_dex_file->GetLocation()
2325 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002326 return false;
2327 }
2328 }
2329
2330 return true;
2331}
2332
David Brazdil7b49e6c2016-09-01 11:06:18 +01002333bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002334 File* file,
2335 OatDexFile* oat_dex_file,
2336 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01002337 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
2338 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002339
2340 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2341 if (input_offset != static_cast<off_t>(0)) {
2342 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2343 << " Expected: 0"
2344 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2345 return false;
2346 }
2347 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2348 return false;
2349 }
2350
2351 // Copy the input dex file using sendfile().
2352 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2353 PLOG(ERROR) << "Failed to copy dex file to oat file."
2354 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2355 return false;
2356 }
2357 if (file->Flush() != 0) {
2358 PLOG(ERROR) << "Failed to flush dex file."
2359 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2360 return false;
2361 }
2362
2363 // Check file position and seek the stream to the end offset.
2364 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2365 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2366 if (actual_offset != static_cast<off_t>(end_offset)) {
2367 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2368 << " Expected: " << end_offset
2369 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2370 return false;
2371 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002372 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002373 if (actual_offset != static_cast<off_t>(end_offset)) {
2374 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2375 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2376 return false;
2377 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002378 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002379 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2380 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2381 return false;
2382 }
2383
2384 return true;
2385}
2386
David Brazdil7b49e6c2016-09-01 11:06:18 +01002387bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002388 OatDexFile* oat_dex_file,
2389 const uint8_t* dex_file) {
2390 // Note: The raw data has already been checked to contain the header
2391 // and all the data that the header specifies as the file size.
2392 DCHECK(dex_file != nullptr);
2393 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2394 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2395
David Brazdil7b49e6c2016-09-01 11:06:18 +01002396 if (!out->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002397 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002398 << " to " << out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002399 return false;
2400 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01002401 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002402 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2403 << " File: " << oat_dex_file->GetLocation();
2404 return false;
2405 }
2406
2407 // Update dex file size and resize class offsets in the OatDexFile.
2408 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002409 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002410 oat_dex_file->dex_file_size_ = header->file_size_;
2411 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2412 return true;
2413}
2414
2415bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2416 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2417
David Brazdil181e1cc2016-09-01 16:38:47 +00002418 off_t initial_offset = rodata->Seek(0, kSeekCurrent);
2419 if (initial_offset == static_cast<off_t>(-1)) {
2420 LOG(ERROR) << "Failed to get current position in " << rodata->GetLocation();
2421 return false;
2422 }
2423
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002424 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2425 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2426 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2427 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2428 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2429 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2430 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2431 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2432 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2433 return false;
2434 }
2435
2436 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2437 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2438
2439 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2440 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2441
2442 // Write OatDexFile.
2443 if (!oat_dex_file->Write(this, rodata)) {
2444 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2445 return false;
2446 }
2447 }
2448
David Brazdil181e1cc2016-09-01 16:38:47 +00002449 // Seek back to the initial position.
2450 if (rodata->Seek(initial_offset, kSeekSet) != initial_offset) {
2451 PLOG(ERROR) << "Failed to seek to initial position. Actual: " << actual_offset
2452 << " Expected: " << initial_offset << " File: " << rodata->GetLocation();
2453 return false;
2454 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002455
David Brazdilb92ba622016-09-01 16:00:30 +00002456 return true;
2457}
2458
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002459bool OatWriter::OpenDexFiles(
2460 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002461 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002462 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2463 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2464 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2465
2466 if (oat_dex_files_.empty()) {
2467 // Nothing to do.
2468 return true;
2469 }
2470
2471 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002472 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
2473
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002474 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002475 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
2476 length,
2477 PROT_READ | PROT_WRITE,
2478 MAP_SHARED,
2479 file->Fd(),
2480 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
2481 /* low_4gb */ false,
2482 file->GetPath().c_str(),
2483 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002484 if (dex_files_map == nullptr) {
2485 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2486 << " error: " << error_msg;
2487 return false;
2488 }
2489 std::vector<std::unique_ptr<const DexFile>> dex_files;
2490 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2491 // Make sure no one messed with input files while we were copying data.
2492 // At the very least we need consistent file size and number of class definitions.
2493 const uint8_t* raw_dex_file =
2494 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2495 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2496 // Note: ValidateDexFileHeader() already logged an error message.
2497 LOG(ERROR) << "Failed to verify written dex file header!"
2498 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2499 << " ~ " << static_cast<const void*>(raw_dex_file);
2500 return false;
2501 }
2502 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2503 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2504 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2505 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2506 << " Output: " << file->GetPath();
2507 return false;
2508 }
2509 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2510 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2511 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2512 << " Output: " << file->GetPath();
2513 return false;
2514 }
2515
2516 // Now, open the dex file.
2517 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2518 oat_dex_file.dex_file_size_,
2519 oat_dex_file.GetLocation(),
2520 oat_dex_file.dex_file_location_checksum_,
2521 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002522 verify,
Aart Bik37d6a3b2016-06-21 18:30:10 -07002523 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002524 &error_msg));
2525 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002526 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2527 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002528 return false;
2529 }
2530 }
2531
2532 *opened_dex_files_map = std::move(dex_files_map);
2533 *opened_dex_files = std::move(dex_files);
2534 return true;
2535}
2536
2537bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01002538 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002539 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2540 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2541
David Brazdil7b49e6c2016-09-01 11:06:18 +01002542 uint32_t expected_offset = oat_data_offset_ + oat_size_;
2543 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
2544 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2545 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
2546 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
2547 return false;
2548 }
2549
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002550 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2551 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2552 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00002553 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
2554
2555 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
2556 oat_dex_file->class_offsets_.empty()) {
2557 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002558 }
David Brazdil181e1cc2016-09-01 16:38:47 +00002559
2560 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
2561 if (table_size == 0u) {
2562 continue;
2563 }
2564
2565 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07002566 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08002567 const DexFile& dex_file = *opened_dex_files[i];
2568 {
2569 std::unique_ptr<TypeLookupTable> type_lookup_table =
2570 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
2571 type_lookup_table_oat_dex_files_.push_back(
2572 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
2573 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
2574 }
2575 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00002576
2577 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002578 size_t initial_offset = oat_size_;
2579 size_t rodata_offset = RoundUp(initial_offset, 4);
2580 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00002581
2582 if (padding_size != 0u) {
2583 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002584 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002585 PLOG(ERROR) << "Failed to write lookup table alignment padding."
2586 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002587 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002588 return false;
2589 }
2590 }
2591
2592 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01002593 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00002594 DCHECK_EQ(table_size, table->RawDataLength());
2595
David Brazdil7b49e6c2016-09-01 11:06:18 +01002596 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002597 PLOG(ERROR) << "Failed to write lookup table."
2598 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01002599 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00002600 return false;
2601 }
2602
2603 oat_dex_file->lookup_table_offset_ = rodata_offset;
2604
David Brazdil7b49e6c2016-09-01 11:06:18 +01002605 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00002606 size_oat_lookup_table_ += table_size;
2607 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002608 }
2609
David Brazdil7b49e6c2016-09-01 11:06:18 +01002610 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00002611 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01002612 << " File: " << oat_rodata->GetLocation();
2613 return false;
2614 }
2615
2616 return true;
2617}
2618
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002619bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002620 if (!kIsVdexEnabled) {
2621 return true;
2622 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002623 // Write checksums
2624 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
2625 if (actual_offset != sizeof(VdexFile::Header)) {
2626 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
2627 << " File: " << vdex_out->GetLocation();
2628 return false;
2629 }
2630
2631 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2632 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2633 if (!vdex_out->WriteFully(
2634 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
2635 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
2636 << vdex_out->GetLocation();
2637 return false;
2638 }
2639 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
2640 }
2641
2642 // Write header.
2643 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002644 if (actual_offset != 0) {
2645 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
2646 << " File: " << vdex_out->GetLocation();
2647 return false;
2648 }
2649
David Brazdil5d5a36b2016-09-14 15:34:10 +01002650 DCHECK_NE(vdex_dex_files_offset_, 0u);
2651 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
2652
2653 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002654 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
2655 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01002656
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002657 VdexFile::Header vdex_header(oat_dex_files_.size(),
2658 dex_section_size,
2659 verifier_deps_section_size,
2660 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01002661 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
2662 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002663 return false;
2664 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002665 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002666
David Brazdil5d5a36b2016-09-14 15:34:10 +01002667 if (!vdex_out->Flush()) {
2668 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
2669 << " File: " << vdex_out->GetLocation();
2670 return false;
2671 }
2672
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002673 return true;
2674}
2675
Vladimir Markof4da6752014-08-01 19:04:18 +01002676bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2677 static const uint8_t kPadding[] = {
2678 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2679 };
2680 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002681 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002682 return false;
2683 }
2684 size_code_alignment_ += aligned_code_delta;
2685 return true;
2686}
2687
Vladimir Marko944da602016-02-19 12:27:55 +00002688void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2689 DCHECK(dex_files_ != nullptr);
2690 DCHECK(relative_patcher_ != nullptr);
2691 DCHECK_NE(oat_data_offset_, 0u);
2692 if (image_writer_ != nullptr && !dex_files_->empty()) {
2693 // The oat data begin may not be initialized yet but the oat file offset is ready.
2694 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2695 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2696 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002697 }
2698}
2699
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002700OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2701 DexFileSource source,
2702 CreateTypeLookupTable create_type_lookup_table)
2703 : source_(source),
2704 create_type_lookup_table_(create_type_lookup_table),
2705 dex_file_size_(0),
2706 offset_(0),
2707 dex_file_location_size_(strlen(dex_file_location)),
2708 dex_file_location_data_(dex_file_location),
2709 dex_file_location_checksum_(0u),
2710 dex_file_offset_(0u),
2711 class_offsets_offset_(0u),
2712 lookup_table_offset_(0u),
2713 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002714}
2715
2716size_t OatWriter::OatDexFile::SizeOf() const {
2717 return sizeof(dex_file_location_size_)
2718 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002719 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002720 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002721 + sizeof(class_offsets_offset_)
2722 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002723}
2724
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002725void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2726 DCHECK_EQ(class_offsets_offset_, 0u);
2727 if (!class_offsets_.empty()) {
2728 // Class offsets are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01002729 size_t initial_offset = oat_writer->oat_size_;
2730 size_t offset = RoundUp(initial_offset, 4);
2731 oat_writer->size_oat_class_offsets_alignment_ += offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002732 class_offsets_offset_ = offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01002733 oat_writer->oat_size_ = offset + GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002734 }
2735}
2736
2737bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2738 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002739 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002740
Vladimir Markoe079e212016-05-25 12:49:49 +01002741 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002742 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002743 return false;
2744 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002745 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002746
Vladimir Markoe079e212016-05-25 12:49:49 +01002747 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002748 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002749 return false;
2750 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002751 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002752
Vladimir Markoe079e212016-05-25 12:49:49 +01002753 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002754 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002755 return false;
2756 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002757 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002758
Vladimir Markoe079e212016-05-25 12:49:49 +01002759 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002760 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002761 return false;
2762 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002763 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002764
Vladimir Markoe079e212016-05-25 12:49:49 +01002765 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002766 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2767 return false;
2768 }
2769 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2770
Vladimir Markoe079e212016-05-25 12:49:49 +01002771 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002772 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2773 return false;
2774 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002775 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002776
2777 return true;
2778}
2779
2780bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002781 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002782 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2783 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002784 return false;
2785 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002786 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002787 return true;
2788}
2789
Brian Carlstromba150c32013-08-27 17:31:03 -07002790OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002791 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002792 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002793 mirror::Class::Status status)
2794 : compiled_methods_(compiled_methods) {
2795 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002796 CHECK_LE(num_non_null_compiled_methods, num_methods);
2797
Brian Carlstrom265091e2013-01-30 14:08:26 -08002798 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002799 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2800
2801 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2802 // apply when there are 0 methods, we just arbitrarily say that 0
2803 // methods means kOatClassNoneCompiled and that we won't use
2804 // kOatClassAllCompiled unless there is at least one compiled
2805 // method. This means in an interpretter only system, we can assert
2806 // that all classes are kOatClassNoneCompiled.
2807 if (num_non_null_compiled_methods == 0) {
2808 type_ = kOatClassNoneCompiled;
2809 } else if (num_non_null_compiled_methods == num_methods) {
2810 type_ = kOatClassAllCompiled;
2811 } else {
2812 type_ = kOatClassSomeCompiled;
2813 }
2814
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002815 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002816 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002817 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002818
2819 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2820 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002821 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002822 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2823 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2824 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2825 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002826 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002827 method_bitmap_size_ = 0;
2828 }
2829
2830 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002831 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002832 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002833 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2834 } else {
2835 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2836 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2837 if (type_ == kOatClassSomeCompiled) {
2838 method_bitmap_->SetBit(i);
2839 }
2840 }
2841 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002842}
2843
Brian Carlstrom265091e2013-01-30 14:08:26 -08002844size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2845 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002846 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2847 if (method_offset == 0) {
2848 return 0;
2849 }
2850 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002851}
2852
2853size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2854 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002855 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002856}
2857
2858size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002859 return sizeof(status_)
2860 + sizeof(type_)
2861 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2862 + method_bitmap_size_
2863 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002864}
2865
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002866bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002867 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002868 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002869 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002870 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002871 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002872 return false;
2873 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002874 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002875
Vladimir Markoe079e212016-05-25 12:49:49 +01002876 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002877 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002878 return false;
2879 }
2880 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002881
Brian Carlstromba150c32013-08-27 17:31:03 -07002882 if (method_bitmap_size_ != 0) {
2883 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002884 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002885 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002886 return false;
2887 }
2888 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002889
Vladimir Markoe079e212016-05-25 12:49:49 +01002890 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002891 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002892 return false;
2893 }
2894 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2895 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002896
Vladimir Markoe079e212016-05-25 12:49:49 +01002897 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002898 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002899 return false;
2900 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002901 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002902 return true;
2903}
2904
Brian Carlstrome24fa612011-09-29 00:53:55 -07002905} // namespace art