blob: 0fd24a8a8f7eed8303604c9b2c18b299d9490fb6 [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
Igor Murashkin545412b2017-08-17 15:26:54 -070019#include <algorithm>
Vladimir Marko9bdf1082016-01-21 12:15:52 +000020#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070021#include <zlib.h>
22
Vladimir Markoc74658b2015-03-31 10:26:41 +010023#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070025#include "base/allocator.h"
Vladimir Marko0eb882b2017-05-15 13:39:18 +010026#include "base/bit_vector-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070027#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000028#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070031#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010032#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010033#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000035#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000036#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070037#include "dex_file_loader.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070038#include "dex_file_types.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070039#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070040#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000041#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010042#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030044#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010045#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010046#include "linker/buffered_output_stream.h"
47#include "linker/file_output_stream.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010048#include "linker/linker_patch.h"
Vladimir Marko0eb882b2017-05-15 13:39:18 +010049#include "linker/method_bss_mapping_encoder.h"
Vladimir Marko944da602016-02-19 12:27:55 +000050#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000051#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/array.h"
53#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010054#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070055#include "mirror/object-inl.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070056#include "standard_dex_file.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010057#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070058#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070059#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070060#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030061#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010062#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010063#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010064#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000065#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070066
67namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000068namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070069
Vladimir Marko9bdf1082016-01-21 12:15:52 +000070namespace { // anonymous namespace
71
Mathieu Chartier120aa282017-08-05 16:03:03 -070072// If we write dex layout info in the oat file.
73static constexpr bool kWriteDexLayoutInfo = true;
74
Igor Murashkin545412b2017-08-17 15:26:54 -070075// Force the OAT method layout to be sorted-by-name instead of
76// the default (class_def_idx, method_idx).
77//
78// Otherwise if profiles are used, that will act as
79// the primary sort order.
80//
81// A bit easier to use for development since oatdump can easily
82// show that things are being re-ordered when two methods aren't adjacent.
83static constexpr bool kOatWriterForceOatCodeLayout = false;
84
85static constexpr bool kOatWriterDebugOatCodeLayout = false;
86
Vladimir Marko9bdf1082016-01-21 12:15:52 +000087typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
88
89const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
90 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
91}
92
Vladimir Markoe079e212016-05-25 12:49:49 +010093class ChecksumUpdatingOutputStream : public OutputStream {
94 public:
95 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
96 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
97
98 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
99 oat_header_->UpdateChecksum(buffer, byte_count);
100 return out_->WriteFully(buffer, byte_count);
101 }
102
103 off_t Seek(off_t offset, Whence whence) OVERRIDE {
104 return out_->Seek(offset, whence);
105 }
106
107 bool Flush() OVERRIDE {
108 return out_->Flush();
109 }
110
111 private:
112 OutputStream* const out_;
113 OatHeader* const oat_header_;
114};
115
Vladimir Marko0c737df2016-08-01 16:33:16 +0100116inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
117 // We want to align the code rather than the preheader.
118 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
119 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
120 return aligned_code_offset - unaligned_code_offset;
121}
122
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000123} // anonymous namespace
124
125// Defines the location of the raw dex file to write.
126class OatWriter::DexFileSource {
127 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800128 enum Type {
129 kNone,
130 kZipEntry,
131 kRawFile,
132 kRawData,
133 };
134
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000135 explicit DexFileSource(ZipEntry* zip_entry)
136 : type_(kZipEntry), source_(zip_entry) {
137 DCHECK(source_ != nullptr);
138 }
139
140 explicit DexFileSource(File* raw_file)
141 : type_(kRawFile), source_(raw_file) {
142 DCHECK(source_ != nullptr);
143 }
144
145 explicit DexFileSource(const uint8_t* dex_file)
146 : type_(kRawData), source_(dex_file) {
147 DCHECK(source_ != nullptr);
148 }
149
Mathieu Chartier497d5262017-02-28 20:17:30 -0800150 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000151 bool IsZipEntry() const { return type_ == kZipEntry; }
152 bool IsRawFile() const { return type_ == kRawFile; }
153 bool IsRawData() const { return type_ == kRawData; }
154
155 ZipEntry* GetZipEntry() const {
156 DCHECK(IsZipEntry());
157 DCHECK(source_ != nullptr);
158 return static_cast<ZipEntry*>(const_cast<void*>(source_));
159 }
160
161 File* GetRawFile() const {
162 DCHECK(IsRawFile());
163 DCHECK(source_ != nullptr);
164 return static_cast<File*>(const_cast<void*>(source_));
165 }
166
167 const uint8_t* GetRawData() const {
168 DCHECK(IsRawData());
169 DCHECK(source_ != nullptr);
170 return static_cast<const uint8_t*>(source_);
171 }
172
173 void Clear() {
174 type_ = kNone;
175 source_ = nullptr;
176 }
177
178 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000179 Type type_;
180 const void* source_;
181};
182
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700183// OatClassHeader is the header only part of the oat class that is required even when compilation
184// is not enabled.
185class OatWriter::OatClassHeader {
186 public:
187 OatClassHeader(uint32_t offset,
188 uint32_t num_non_null_compiled_methods,
189 uint32_t num_methods,
190 mirror::Class::Status status)
191 : status_(status),
192 offset_(offset) {
193 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
194 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
195 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
196 if (num_non_null_compiled_methods == 0) {
197 type_ = kOatClassNoneCompiled;
198 } else if (num_non_null_compiled_methods == num_methods) {
199 type_ = kOatClassAllCompiled;
200 } else {
201 type_ = kOatClassSomeCompiled;
202 }
203 }
204
205 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
206
207 static size_t SizeOf() {
208 return sizeof(status_) + sizeof(type_);
209 }
210
211 // Data to write.
212 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
213 int16_t status_;
214
215 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
216 uint16_t type_;
217
218 // Offset of start of OatClass from beginning of OatHeader. It is
219 // used to validate file position when writing.
220 uint32_t offset_;
221};
222
223// The actual oat class body contains the information about compiled methods. It is only required
224// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000225class OatWriter::OatClass {
226 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700227 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100228 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700229 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000230 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000231 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700232 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000233
234 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
235 return compiled_methods_[class_def_method_index];
236 }
237
Vladimir Marko49b0f452015-12-10 13:49:19 +0000238 // CompiledMethods for each class_def_method_index, or null if no method is available.
239 dchecked_vector<CompiledMethod*> compiled_methods_;
240
241 // Offset from OatClass::offset_ to the OatMethodOffsets for the
242 // class_def_method_index. If 0, it means the corresponding
243 // CompiledMethod entry in OatClass::compiled_methods_ should be
244 // null and that the OatClass::type_ should be kOatClassBitmap.
245 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
246
247 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248 uint32_t method_bitmap_size_;
249
250 // bit vector indexed by ClassDef method index. When
251 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
252 // method has an OatMethodOffsets in methods_offsets_, otherwise
253 // the entry was ommited to save space. If OatClassType::type_ is
254 // not is kOatClassBitmap, the bitmap will be null.
255 std::unique_ptr<BitVector> method_bitmap_;
256
257 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
258 // present in the OatClass. Note that some may be missing if
259 // OatClass::compiled_methods_ contains null values (and
260 // oat_method_offsets_offsets_from_oat_class_ should contain 0
261 // values in this case).
262 dchecked_vector<OatMethodOffsets> method_offsets_;
263 dchecked_vector<OatQuickMethodHeader> method_headers_;
264
265 private:
266 size_t GetMethodOffsetsRawSize() const {
267 return method_offsets_.size() * sizeof(method_offsets_[0]);
268 }
269
270 DISALLOW_COPY_AND_ASSIGN(OatClass);
271};
272
273class OatWriter::OatDexFile {
274 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000275 OatDexFile(const char* dex_file_location,
276 DexFileSource source,
277 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000278 OatDexFile(OatDexFile&& src) = default;
279
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000280 const char* GetLocation() const {
281 return dex_file_location_data_;
282 }
283
Vladimir Marko49b0f452015-12-10 13:49:19 +0000284 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000285 bool Write(OatWriter* oat_writer, OutputStream* out) const;
286 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
287
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100288 size_t GetClassOffsetsRawSize() const {
289 return class_offsets_.size() * sizeof(class_offsets_[0]);
290 }
291
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000292 // The source of the dex file.
293 DexFileSource source_;
294
295 // Whether to create the type lookup table.
296 CreateTypeLookupTable create_type_lookup_table_;
297
298 // Dex file size. Initialized when writing the dex file.
299 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000300
301 // Offset of start of OatDexFile from beginning of OatHeader. It is
302 // used to validate file position when writing.
303 size_t offset_;
304
305 // Data to write.
306 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000307 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000308 uint32_t dex_file_location_checksum_;
309 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000310 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000311 uint32_t lookup_table_offset_;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100312 uint32_t method_bss_mapping_offset_;
Mathieu Chartier120aa282017-08-05 16:03:03 -0700313 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000314
315 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000316 dchecked_vector<uint32_t> class_offsets_;
317
Mathieu Chartier120aa282017-08-05 16:03:03 -0700318 // Dex section layout info to serialize.
319 DexLayoutSections dex_sections_layout_;
320
Vladimir Marko49b0f452015-12-10 13:49:19 +0000321 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000322 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
323};
324
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100325#define DCHECK_OFFSET() \
326 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
327 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
328
329#define DCHECK_OFFSET_() \
330 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
331 << "file_offset=" << file_offset << " offset_=" << offset_
332
Jeff Hao608f2ce2016-10-19 11:17:11 -0700333OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings, ProfileCompilationInfo* info)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000334 : write_state_(WriteState::kAddingDexFileSources),
335 timings_(timings),
336 raw_dex_files_(),
337 zip_archives_(),
338 zipped_dex_files_(),
339 zipped_dex_file_locations_(),
340 compiler_driver_(nullptr),
341 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800342 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000343 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100344 vdex_size_(0u),
345 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100346 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100347 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100348 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000349 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000350 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100351 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000352 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100353 bss_method_entry_references_(),
354 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000355 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000356 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100357 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100358 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700359 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100360 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000361 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700362 size_dex_file_alignment_(0),
363 size_executable_offset_alignment_(0),
364 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700365 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700366 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100367 size_verifier_deps_(0),
368 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100369 size_quickening_info_(0),
370 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700371 size_interpreter_to_interpreter_bridge_(0),
372 size_interpreter_to_compiled_code_bridge_(0),
373 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800374 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700375 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700376 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700377 size_quick_to_interpreter_bridge_(0),
378 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100379 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700380 size_code_(0),
381 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100382 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100383 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700384 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700385 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700386 size_oat_dex_file_location_size_(0),
387 size_oat_dex_file_location_data_(0),
388 size_oat_dex_file_location_checksum_(0),
389 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000390 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000391 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700392 size_oat_dex_file_dex_layout_sections_offset_(0),
393 size_oat_dex_file_dex_layout_sections_(0),
394 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100395 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000396 size_oat_lookup_table_alignment_(0),
397 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000398 size_oat_class_offsets_alignment_(0),
399 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700400 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700401 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700402 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100403 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100404 size_method_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000405 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700406 absolute_patch_locations_(),
407 profile_compilation_info_(info) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000408}
409
410bool OatWriter::AddDexFileSource(const char* filename,
411 const char* location,
412 CreateTypeLookupTable create_type_lookup_table) {
413 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
414 uint32_t magic;
415 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700416 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
417 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000418 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
419 return false;
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700420 } else if (DexFileLoader::IsValidMagic(magic)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000421 // The file is open for reading, not writing, so it's OK to let the File destructor
422 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700423 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000424 oat_dex_files_.emplace_back(location,
425 DexFileSource(raw_dex_files_.back().get()),
426 create_type_lookup_table);
427 } else if (IsZipMagic(magic)) {
428 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
429 return false;
430 }
431 } else {
432 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
433 return false;
434 }
435 return true;
436}
437
438// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700439bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000440 const char* location,
441 CreateTypeLookupTable create_type_lookup_table) {
442 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
443 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700444 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000445 ZipArchive* zip_archive = zip_archives_.back().get();
446 if (zip_archive == nullptr) {
447 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
448 << error_msg;
449 return false;
450 }
451 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700452 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000453 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
454 if (entry == nullptr) {
455 break;
456 }
457 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700458 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000459 const char* full_location = zipped_dex_file_locations_.back().c_str();
460 oat_dex_files_.emplace_back(full_location,
461 DexFileSource(zipped_dex_files_.back().get()),
462 create_type_lookup_table);
463 }
464 if (zipped_dex_file_locations_.empty()) {
465 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
466 return false;
467 }
468 return true;
469}
470
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000471// Add dex file source(s) from a vdex file specified by a file handle.
472bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
473 const char* location,
474 CreateTypeLookupTable create_type_lookup_table) {
475 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
476 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000477 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000478 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
479 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000480 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
481 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000482 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700483
484 if (!DexFileLoader::IsValidMagic(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000485 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
486 return false;
487 }
488 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700489 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000490 const char* full_location = zipped_dex_file_locations_.back().c_str();
491 oat_dex_files_.emplace_back(full_location,
492 DexFileSource(current_dex_data),
493 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000494 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000495 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000496
497 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
498 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
499 return false;
500 }
501
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000502 if (oat_dex_files_.empty()) {
503 LOG(ERROR) << "No dex files in vdex file created from " << location;
504 return false;
505 }
506 return true;
507}
508
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000509// Add dex file source from raw memory.
510bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
511 const char* location,
512 uint32_t location_checksum,
513 CreateTypeLookupTable create_type_lookup_table) {
514 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
515 if (data.size() < sizeof(DexFile::Header)) {
516 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
517 << data.size() << " File: " << location;
518 return false;
519 }
520 if (!ValidateDexFileHeader(data.data(), location)) {
521 return false;
522 }
523 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
524 if (data.size() < header->file_size_) {
525 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
526 << " file size from header: " << header->file_size_ << " File: " << location;
527 return false;
528 }
529
530 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
531 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
532 return true;
533}
534
Calin Juravle1ce70852017-06-28 10:59:03 -0700535dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
536 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000537 locations.reserve(oat_dex_files_.size());
538 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
539 locations.push_back(oat_dex_file.GetLocation());
540 }
541 return locations;
542}
543
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700544bool OatWriter::MayHaveCompiledMethods() const {
545 return CompilerFilter::IsAnyCompilationEnabled(
546 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
547}
548
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000549bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100550 File* vdex_file,
551 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000552 InstructionSet instruction_set,
553 const InstructionSetFeatures* instruction_set_features,
554 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800555 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000556 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
558 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
559 CHECK(write_state_ == WriteState::kAddingDexFileSources);
560
David Brazdil7b49e6c2016-09-01 11:06:18 +0100561 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
562 if (!RecordOatDataOffset(oat_rodata)) {
563 return false;
564 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000565
566 std::unique_ptr<MemMap> dex_files_map;
567 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100568
569 // Initialize VDEX and OAT headers.
570 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000571 // Reserve space for Vdex header and checksums.
572 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100573 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100574 oat_size_ = InitOatHeader(instruction_set,
575 instruction_set_features,
576 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
577 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100578
579 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
580
581 if (kIsVdexEnabled) {
Andreas Gampe8bdda5a2017-06-08 15:30:36 -0700582 std::unique_ptr<BufferedOutputStream> vdex_out =
583 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100584 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000585 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100586 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
587 return false;
588 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100589 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000590 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100591 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000592 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100593 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
594 return false;
595 }
596
597 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
598 // difficult because we're not using the OutputStream directly.
599 if (!oat_dex_files_.empty()) {
600 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
601 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
602 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000603 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000604
Mathieu Chartier120aa282017-08-05 16:03:03 -0700605 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000606 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
607 return false;
608 }
609
Mathieu Chartier120aa282017-08-05 16:03:03 -0700610 // Write dex layout sections into the oat file.
611 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
612 return false;
613 }
614
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000615 *opened_dex_files_map = std::move(dex_files_map);
616 *opened_dex_files = std::move(dex_files);
617 write_state_ = WriteState::kPrepareLayout;
618 return true;
619}
620
Vladimir Marko74527972016-11-29 15:57:32 +0000621void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000622 CHECK(write_state_ == WriteState::kPrepareLayout);
623
Vladimir Marko944da602016-02-19 12:27:55 +0000624 relative_patcher_ = relative_patcher;
625 SetMultiOatRelativePatcherAdjustment();
626
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000627 if (compiling_boot_image_) {
628 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800629 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100630 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000631 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100632
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100633 {
634 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
635 InitBssLayout(instruction_set);
636 }
637
David Brazdil7b49e6c2016-09-01 11:06:18 +0100638 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800639 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100640 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
641 offset = InitClassOffsets(offset);
642 }
643 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000644 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800645 offset = InitOatClasses(offset);
646 }
647 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100648 TimingLogger::ScopedTiming split("InitMethodBssMappings", timings_);
649 offset = InitMethodBssMappings(offset);
650 }
651 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000652 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100653 offset = InitOatMaps(offset);
654 }
655 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100656 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
657 oat_header_->SetOatDexFilesOffset(offset);
658 offset = InitOatDexFiles(offset);
659 }
660 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000661 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800662 offset = InitOatCode(offset);
663 }
664 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000665 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800666 offset = InitOatCodeDexFiles(offset);
667 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100668 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100669 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100670
Brian Carlstrome24fa612011-09-29 00:53:55 -0700671 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800672 if (compiling_boot_image_) {
673 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000674 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800675 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000676
677 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700678}
679
Ian Rogers0571d352011-11-03 19:51:38 -0700680OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700681}
682
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100683class OatWriter::DexMethodVisitor {
684 public:
685 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100686 : writer_(writer),
687 offset_(offset),
688 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700689 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100690
691 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
692 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700693 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100694 dex_file_ = dex_file;
695 class_def_index_ = class_def_index;
696 return true;
697 }
698
699 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
700
701 virtual bool EndClass() {
702 if (kIsDebugBuild) {
703 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700704 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100705 }
706 return true;
707 }
708
709 size_t GetOffset() const {
710 return offset_;
711 }
712
713 protected:
714 virtual ~DexMethodVisitor() { }
715
716 OatWriter* const writer_;
717
718 // The offset is usually advanced for each visited method by the derived class.
719 size_t offset_;
720
721 // The dex file and class def index are set in StartClass().
722 const DexFile* dex_file_;
723 size_t class_def_index_;
724};
725
726class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
727 public:
728 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100729 : DexMethodVisitor(writer, offset),
730 oat_class_index_(0u),
731 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100732
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100733 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100734 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700735 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
736 // There are no oat classes if there aren't any compiled methods.
737 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
738 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100739 method_offsets_index_ = 0u;
740 return true;
741 }
742
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100743 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100744 ++oat_class_index_;
745 return DexMethodVisitor::EndClass();
746 }
747
748 protected:
749 size_t oat_class_index_;
750 size_t method_offsets_index_;
751};
752
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100753static bool HasCompiledCode(const CompiledMethod* method) {
754 // The dextodexcompiler puts the quickening info table into the CompiledMethod
755 // for simplicity. For such methods, we will emit an OatQuickMethodHeader
756 // only when vdex is disabled.
757 return method != nullptr && (!method->GetQuickCode().empty() || !kIsVdexEnabled);
758}
759
760static bool HasQuickeningInfo(const CompiledMethod* method) {
761 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
762}
763
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100764class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
765 public:
766 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
767 : DexMethodVisitor(writer, /* offset */ 0u) {}
768
769 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
770 const ClassDataItemIterator& it) OVERRIDE {
771 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
772 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
773 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100774 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100775 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
776 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
777 MethodReference target_method = patch.TargetMethod();
778 auto refs_it = writer_->bss_method_entry_references_.find(target_method.dex_file);
779 if (refs_it == writer_->bss_method_entry_references_.end()) {
780 refs_it = writer_->bss_method_entry_references_.Put(
781 target_method.dex_file,
782 BitVector(target_method.dex_file->NumMethodIds(),
783 /* expandable */ false,
784 Allocator::GetMallocAllocator()));
785 refs_it->second.ClearAllBits();
786 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700787 refs_it->second.SetBit(target_method.index);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100788 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
789 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
790 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
791 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
792 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
793 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
794 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100795 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
796 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100797 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100798 }
799 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100800 } else {
801 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100802 }
803 return true;
804 }
805};
806
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100807class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
808 public:
809 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100810 : DexMethodVisitor(writer, offset),
811 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100812 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000813 size_t num_classes = 0u;
814 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
815 num_classes += oat_dex_file.class_offsets_.size();
816 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700817 // If we aren't compiling only reserve headers.
818 writer_->oat_class_headers_.reserve(num_classes);
819 if (writer->MayHaveCompiledMethods()) {
820 writer->oat_classes_.reserve(num_classes);
821 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100822 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100823 // If there are any classes, the class offsets allocation aligns the offset.
824 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100825 }
826
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100827 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100828 DexMethodVisitor::StartClass(dex_file, class_def_index);
829 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100830 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100831 return true;
832 }
833
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300834 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100835 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100836 // Fill in the compiled_methods_ array for methods that have a
837 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100838 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100839 // OatMethodOffsets for the compiled methods.
840 uint32_t method_idx = it.GetMemberIndex();
841 CompiledMethod* compiled_method =
842 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
843 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100844 if (HasCompiledCode(compiled_method)) {
845 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100846 }
847 return true;
848 }
849
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100850 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100851 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100852 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700853 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
854 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700855 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
856 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700857 // The oat class status is used only for verification of resolved classes,
858 // so use kStatusErrorResolved whether the class was resolved or unresolved
859 // during compile-time verification.
860 status = mirror::Class::kStatusErrorResolved;
861 } else {
862 status = mirror::Class::kStatusNotReady;
863 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100864 }
865
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700866 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100867 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700868 compiled_methods_.size(),
869 status);
870 OatClassHeader& header = writer_->oat_class_headers_.back();
871 offset_ += header.SizeOf();
872 if (writer_->MayHaveCompiledMethods()) {
873 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100874 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700875 header.type_);
876 offset_ += writer_->oat_classes_.back().SizeOf();
877 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100878 return DexMethodVisitor::EndClass();
879 }
880
881 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000882 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100883 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100884};
885
Igor Murashkin545412b2017-08-17 15:26:54 -0700886// CompiledMethod + metadata required to do ordered method layout.
887//
888// See also OrderedMethodVisitor.
889struct OatWriter::OrderedMethodData {
890 ProfileCompilationInfo::MethodHotness method_hotness;
891 OatClass* oat_class;
892 CompiledMethod* compiled_method;
893 MethodReference method_reference;
894 size_t method_offsets_index;
895
896 size_t class_def_index;
897 uint32_t access_flags;
898 const DexFile::CodeItem* code_item;
899
900 // A value of -1 denotes missing debug info
901 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
902 // Index into writer_->method_info_
903 size_t debug_info_idx;
904
905 bool HasDebugInfo() const {
906 return debug_info_idx != kDebugInfoIdxInvalid;
907 }
908
909 // Bin each method according to the profile flags.
910 //
911 // Groups by e.g.
912 // -- not hot at all
913 // -- hot
914 // -- hot and startup
915 // -- hot and post-startup
916 // -- hot and startup and poststartup
917 // -- startup
918 // -- startup and post-startup
919 // -- post-startup
920 //
921 // (See MethodHotness enum definition for up-to-date binning order.)
922 bool operator<(const OrderedMethodData& other) const {
923 if (kOatWriterForceOatCodeLayout) {
924 // Development flag: Override default behavior by sorting by name.
925
926 std::string name = method_reference.PrettyMethod();
927 std::string other_name = other.method_reference.PrettyMethod();
928 return name < other_name;
929 }
930
931 // Use the profile's method hotness to determine sort order.
932 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
933 return true;
934 }
935
936 // Default: retain the original order.
937 return false;
938 }
939
940 private:
941 // Used to determine relative order for OAT code layout when determining
942 // binning.
943 size_t GetMethodHotnessOrder() const {
944 bool hotness[] = {
945 method_hotness.IsHot(),
946 method_hotness.IsStartup(),
947 method_hotness.IsPostStartup()
948 };
949
950
951 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
952 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
953 // time that memory is referenced in the process.
954
955 size_t hotness_bits = 0;
956 for (size_t i = 0; i < arraysize(hotness); ++i) {
957 if (hotness[i]) {
958 hotness_bits |= (1 << i);
959 }
960 }
961
962 if (kIsDebugBuild) {
963 // Check for bins that are always-empty given a real profile.
964 if (method_hotness.IsHot() &&
965 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
966 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -0700967 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
968 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -0700969 // This is not fatal, so only warn.
970 }
971 }
972
973 return hotness_bits;
974 }
975};
976
977// Given a queue of CompiledMethod in some total order,
978// visit each one in that order.
979class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100980 public:
Igor Murashkin545412b2017-08-17 15:26:54 -0700981 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
982 : ordered_methods_(std::move(ordered_methods)) {
983 }
984
985 virtual ~OrderedMethodVisitor() {}
986
987 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
988 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
989 if (!VisitStart()) {
990 return false;
991 }
992
993 for (const OrderedMethodData& method_data : ordered_methods_) {
994 if (!VisitMethod(method_data)) {
995 return false;
996 }
997 }
998
999 return VisitComplete();
1000 }
1001
1002 // Invoked once at the beginning, prior to visiting anything else.
1003 //
1004 // Return false to abort further visiting.
1005 virtual bool VisitStart() { return true; }
1006
1007 // Invoked repeatedly in the order specified by `ordered_methods`.
1008 //
1009 // Return false to short-circuit and to stop visiting further methods.
1010 virtual bool VisitMethod(const OrderedMethodData& method_data)
1011 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1012
1013 // Invoked once at the end, after every other method has been successfully visited.
1014 //
1015 // Return false to indicate the overall `Visit` has failed.
1016 virtual bool VisitComplete() = 0;
1017
1018 OrderedMethodList ReleaseOrderedMethods() {
1019 return std::move(ordered_methods_);
1020 }
1021
1022 private:
1023 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1024 // Methods can be inserted more than once in case of duplicated methods.
1025 OrderedMethodList ordered_methods_;
1026};
1027
1028// Visit every compiled method in order to determine its order within the OAT file.
1029// Methods from the same class do not need to be adjacent in the OAT code.
1030class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1031 public:
1032 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1033 : OatDexMethodVisitor(writer, offset) {
1034 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001035
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001036 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001037 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001038 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001039 }
1040
Igor Murashkin545412b2017-08-17 15:26:54 -07001041 bool VisitMethod(size_t class_def_method_index,
1042 const ClassDataItemIterator& it)
1043 OVERRIDE
1044 REQUIRES_SHARED(Locks::mutator_lock_) {
1045 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1046
Vladimir Marko49b0f452015-12-10 13:49:19 +00001047 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001048 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1049
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001050 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001051 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001052
Igor Murashkin545412b2017-08-17 15:26:54 -07001053 {
1054 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1055 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1056 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001057
Igor Murashkin545412b2017-08-17 15:26:54 -07001058 // Debug method info must be pushed in the original order
1059 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1060 // ElfCompilationUnitWriter::Write requires this.
1061 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1062 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1063 writer_->method_info_.push_back(info);
1064
1065 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1066 // once we know the offsets.
1067 //
1068 // Store the index into writer_->method_info_ since future push-backs
1069 // could reallocate and change the underlying data address.
1070 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001071 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001072 }
1073
1074 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1075
1076 // Lookup method hotness from profile, if available.
1077 // Otherwise assume a default of none-hotness.
1078 ProfileCompilationInfo::MethodHotness method_hotness =
1079 writer_->profile_compilation_info_ != nullptr
1080 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1081 : ProfileCompilationInfo::MethodHotness();
1082
1083 // Handle duplicate methods by pushing them repeatedly.
1084 OrderedMethodData method_data = {
1085 method_hotness,
1086 oat_class,
1087 compiled_method,
1088 method_ref,
1089 method_offsets_index_,
1090 class_def_index_,
1091 it.GetMethodAccessFlags(),
1092 it.GetMethodCodeItem(),
1093 debug_info_idx
1094 };
1095 ordered_methods_.push_back(method_data);
1096
1097 method_offsets_index_++;
1098 }
1099
1100 return true;
1101 }
1102
1103 OrderedMethodList ReleaseOrderedMethods() {
1104 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1105 // Sort by the method ordering criteria (in OrderedMethodData).
1106 // Since most methods will have the same ordering criteria,
1107 // we preserve the original insertion order within the same sort order.
1108 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1109 } else {
1110 // The profile-less behavior is as if every method had 0 hotness
1111 // associated with it.
1112 //
1113 // Since sorting all methods with hotness=0 should give back the same
1114 // order as before, don't do anything.
1115 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1116 }
1117
1118 return std::move(ordered_methods_);
1119 }
1120
1121 private:
1122 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1123 // Methods can be inserted more than once in case of duplicated methods.
1124 OrderedMethodList ordered_methods_;
1125};
1126
1127// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1128class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1129 public:
1130 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1131 size_t offset,
1132 OrderedMethodList ordered_methods)
1133 : LayoutReserveOffsetCodeMethodVisitor(writer,
1134 offset,
1135 writer->GetCompilerDriver()->GetCompilerOptions(),
1136 std::move(ordered_methods)) {
1137 }
1138
1139 virtual bool VisitComplete() OVERRIDE {
1140 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1141 if (generate_debug_info_) {
1142 std::vector<debug::MethodDebugInfo> thunk_infos =
1143 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1144 writer_->method_info_.insert(writer_->method_info_.end(),
1145 std::make_move_iterator(thunk_infos.begin()),
1146 std::make_move_iterator(thunk_infos.end()));
1147 }
1148 return true;
1149 }
1150
1151 virtual bool VisitMethod(const OrderedMethodData& method_data)
1152 OVERRIDE
1153 REQUIRES_SHARED(Locks::mutator_lock_) {
1154 OatClass* oat_class = method_data.oat_class;
1155 CompiledMethod* compiled_method = method_data.compiled_method;
1156 const MethodReference& method_ref = method_data.method_reference;
1157 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1158 size_t class_def_index = method_data.class_def_index;
1159 uint32_t access_flags = method_data.access_flags;
1160 const DexFile::CodeItem* code_item = method_data.code_item;
1161 bool has_debug_info = method_data.HasDebugInfo();
1162 size_t debug_info_idx = method_data.debug_info_idx;
1163
1164 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1165
1166 // Derived from CompiledMethod.
1167 uint32_t quick_code_offset = 0;
1168
1169 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1170 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1171 uint32_t thumb_offset = compiled_method->CodeDelta();
1172
1173 // Deduplicate code arrays if we are not producing debuggable code.
1174 bool deduped = true;
1175 if (debuggable_) {
1176 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1177 if (quick_code_offset != 0u) {
1178 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1179 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001180 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001181 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1182 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001183 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001184
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001185 if (code_size != 0) {
Vladimir Marko1b404a82017-09-01 13:35:26 +01001186 if (relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001187 // TODO: Should this be a hard failure?
1188 LOG(WARNING) << "Multiple definitions of "
Igor Murashkin545412b2017-08-17 15:26:54 -07001189 << method_ref.dex_file->PrettyMethod(method_ref.index)
Vladimir Marko1b404a82017-09-01 13:35:26 +01001190 << " offsets " << relative_patcher_->GetOffset(method_ref)
Vladimir Marko944da602016-02-19 12:27:55 +00001191 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001192 } else {
Vladimir Marko1b404a82017-09-01 13:35:26 +01001193 relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001194 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001195 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001196 } else {
1197 quick_code_offset = dedupe_map_.GetOrCreate(
1198 compiled_method,
1199 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1200 deduped = false;
1201 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1202 });
1203 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001204
Igor Murashkin545412b2017-08-17 15:26:54 -07001205 if (code_size != 0) {
1206 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1207 // TODO: Should this be a hard failure?
1208 LOG(WARNING) << "Multiple definitions of "
1209 << method_ref.dex_file->PrettyMethod(method_ref.index)
1210 << " offsets " << relative_patcher_->GetOffset(method_ref)
1211 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001212 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001213 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1214 }
1215 }
1216
1217 // Update quick method header.
1218 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1219 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1220 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1221 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1222 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1223 // to 0-offset and we need to adjust it by code_offset.
1224 uint32_t code_offset = quick_code_offset - thumb_offset;
1225 if (!compiled_method->GetQuickCode().empty()) {
1226 // If the code is compiled, we write the offset of the stack map relative
1227 // to the code,
1228 if (vmap_table_offset != 0u) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001229 vmap_table_offset += code_offset;
1230 DCHECK_LT(vmap_table_offset, code_offset);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001231 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001232 if (method_info_offset != 0u) {
1233 method_info_offset += code_offset;
1234 DCHECK_LT(method_info_offset, code_offset);
1235 }
1236 } else {
1237 CHECK(!kIsVdexEnabled);
1238 // We write the offset of the quickening info relative to the code.
1239 vmap_table_offset += code_offset;
1240 DCHECK_LT(vmap_table_offset, code_offset);
1241 }
1242 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1243 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1244 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1245 *method_header = OatQuickMethodHeader(vmap_table_offset,
1246 method_info_offset,
1247 frame_size_in_bytes,
1248 core_spill_mask,
1249 fp_spill_mask,
1250 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001251
Igor Murashkin545412b2017-08-17 15:26:54 -07001252 if (!deduped) {
1253 // Update offsets. (Checksum is updated when writing.)
1254 offset_ += sizeof(*method_header); // Method header is prepended before code.
1255 offset_ += code_size;
1256 // Record absolute patch locations.
1257 if (!compiled_method->GetPatches().empty()) {
1258 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1259 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1260 if (!patch.IsPcRelative()) {
1261 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001262 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001263 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001264 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001265 }
1266
Igor Murashkin545412b2017-08-17 15:26:54 -07001267 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1268 if (generate_debug_info_ && code_size != 0) {
1269 DCHECK(has_debug_info);
1270
1271 bool has_code_info = method_header->IsOptimized();
1272 // Record debug information for this function if we are doing that.
1273 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1274 DCHECK(info.trampoline_name.empty());
1275 info.dex_file = method_ref.dex_file;
1276 info.class_def_index = class_def_index;
1277 info.dex_method_index = method_ref.index;
1278 info.access_flags = access_flags;
1279 info.code_item = code_item;
1280 info.isa = compiled_method->GetInstructionSet();
1281 info.deduped = deduped;
1282 info.is_native_debuggable = native_debuggable_;
1283 info.is_optimized = method_header->IsOptimized();
1284 info.is_code_address_text_relative = true;
1285 info.code_address = code_offset - executable_offset_;
1286 info.code_size = code_size;
1287 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1288 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1289 info.cfi = compiled_method->GetCFIInfo();
1290 } else {
1291 DCHECK(!has_debug_info);
1292 }
1293
1294 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1295 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1296 offsets->code_offset_ = quick_code_offset;
1297
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001298 return true;
1299 }
1300
Igor Murashkin545412b2017-08-17 15:26:54 -07001301 size_t GetOffset() const {
1302 return offset_;
1303 }
1304
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001305 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001306 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1307 size_t offset,
1308 const CompilerOptions& compiler_options,
1309 OrderedMethodList ordered_methods)
1310 : OrderedMethodVisitor(std::move(ordered_methods)),
1311 writer_(writer),
1312 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001313 relative_patcher_(writer->relative_patcher_),
1314 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1315 debuggable_(compiler_options.GetDebuggable()),
1316 native_debuggable_(compiler_options.GetNativeDebuggable()),
1317 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1318 writer->absolute_patch_locations_.reserve(
1319 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1320 }
1321
Vladimir Marko20f85592015-03-19 10:07:02 +00001322 struct CodeOffsetsKeyComparator {
1323 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001324 // Code is deduplicated by CompilerDriver, compare only data pointers.
1325 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1326 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001327 }
1328 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001329 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1330 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001331 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001332 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1333 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1334 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001335 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1336 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001337 }
1338 return false;
1339 }
1340 };
1341
David Srbecky009e2a62015-04-15 02:46:30 +01001342 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001343 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001344 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001345 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001346 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1347 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001348 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1349 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1350 }
1351
Igor Murashkin545412b2017-08-17 15:26:54 -07001352 OatWriter* writer_;
1353
1354 // Offset of the code of the compiled methods.
1355 size_t offset_;
1356
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001357 // Deduplication is already done on a pointer basis by the compiler driver,
1358 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001359 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001360
Vladimir Marko1b404a82017-09-01 13:35:26 +01001361 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001362 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001363 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001364 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001365 const bool native_debuggable_;
1366 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001367};
1368
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001369class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1370 public:
1371 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001372 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001373
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001374 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001375 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001376 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001377 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1378
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001379 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001380 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001381 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001382
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001383 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1384 uint32_t map_size = map.size() * sizeof(map[0]);
1385 if (map_size != 0u) {
1386 size_t offset = dedupe_map_.GetOrCreate(
1387 map.data(),
1388 [this, map_size]() {
1389 uint32_t new_offset = offset_;
1390 offset_ += map_size;
1391 return new_offset;
1392 });
1393 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1394 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1395 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001396 }
1397 ++method_offsets_index_;
1398 }
1399
1400 return true;
1401 }
1402
1403 private:
1404 // Deduplication is already done on a pointer basis by the compiler driver,
1405 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001406 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001407};
1408
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001409class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1410 public:
1411 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1412
1413 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001414 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001415 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1416 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1417
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001418 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001419 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1420 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1421 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1422 const uint32_t map_size = map.size() * sizeof(map[0]);
1423 if (map_size != 0u) {
1424 size_t offset = dedupe_map_.GetOrCreate(
1425 map.data(),
1426 [this, map_size]() {
1427 uint32_t new_offset = offset_;
1428 offset_ += map_size;
1429 return new_offset;
1430 });
1431 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1432 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1433 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1434 }
1435 ++method_offsets_index_;
1436 }
1437
1438 return true;
1439 }
1440
1441 private:
1442 // Deduplication is already done on a pointer basis by the compiler driver,
1443 // so we can simply compare the pointers to find out if things are duplicated.
1444 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1445};
1446
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001447class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1448 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001449 InitImageMethodVisitor(OatWriter* writer,
1450 size_t offset,
1451 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001452 : OatDexMethodVisitor(writer, offset),
1453 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001454 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001455 dex_files_(dex_files),
1456 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001457
1458 // Handle copied methods here. Copy pointer to quick code from
1459 // an origin method to a copied method only if they are
1460 // in the same oat file. If the origin and the copied methods are
1461 // in different oat files don't touch the copied method.
1462 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001463 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001464 REQUIRES_SHARED(Locks::mutator_lock_) {
1465 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1466 // Skip classes that are not in the image.
1467 if (!IsImageClass()) {
1468 return true;
1469 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001470 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001471 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1472 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1473 if (klass != nullptr) {
1474 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1475 // Find origin method. Declaring class and dex_method_idx
1476 // in the copied method should be the same as in the origin
1477 // method.
1478 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001479 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001480 declaring_class->GetDexCache(),
1481 method.GetDexMethodIndex(),
1482 pointer_size_);
1483 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001484 CHECK(!origin->IsDirect());
1485 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001486 if (IsInOatFile(&declaring_class->GetDexFile())) {
1487 const void* code_ptr =
1488 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1489 if (code_ptr == nullptr) {
1490 methods_to_process_.push_back(std::make_pair(&method, origin));
1491 } else {
1492 method.SetEntryPointFromQuickCompiledCodePtrSize(
1493 code_ptr, pointer_size_);
1494 }
1495 }
1496 }
1497 }
1498 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001499 }
1500
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001501 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001502 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001503 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001504 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001505 return true;
1506 }
1507
Vladimir Marko49b0f452015-12-10 13:49:19 +00001508 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001509 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1510
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001511 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001512 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001513 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1514 offsets = oat_class->method_offsets_[method_offsets_index_];
1515 ++method_offsets_index_;
1516 }
1517
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001518 Thread* self = Thread::Current();
1519 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001520 ArtMethod* method;
1521 if (writer_->HasBootImage()) {
1522 const InvokeType invoke_type = it.GetMethodInvokeType(
1523 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001524 // Unchecked as we hold mutator_lock_ on entry.
1525 ScopedObjectAccessUnchecked soa(self);
1526 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001527 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001528 *dex_file_,
1529 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001530 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001531 ScopedNullHandle<mirror::ClassLoader>(),
1532 nullptr,
1533 invoke_type);
1534 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001535 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001536 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001537 self->AssertPendingException();
1538 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001539 std::string dump = exc->Dump();
1540 LOG(FATAL) << dump;
1541 UNREACHABLE();
1542 }
1543 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001544 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001545 // It may not be resolved if the class failed to verify, in this case, don't set the
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001546 // entrypoint. This is not fatal since we shall use a resolution method.
1547 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001548 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001549 if (method != nullptr &&
1550 compiled_method != nullptr &&
1551 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001552 method->SetEntryPointFromQuickCompiledCodePtrSize(
1553 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1554 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001555
1556 return true;
1557 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001558
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001559 // Check whether current class is image class
1560 bool IsImageClass() {
1561 const DexFile::TypeId& type_id =
1562 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1563 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1564 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1565 }
1566
1567 // Check whether specified dex file is in the compiled oat file.
1568 bool IsInOatFile(const DexFile* dex_file) {
1569 return ContainsElement(*dex_files_, dex_file);
1570 }
1571
1572 // Assign a pointer to quick code for copied methods
1573 // not handled in the method StartClass
1574 void Postprocess() {
1575 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1576 ArtMethod* method = p.first;
1577 ArtMethod* origin = p.second;
1578 const void* code_ptr =
1579 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1580 if (code_ptr != nullptr) {
1581 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1582 }
1583 }
1584 }
1585
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001586 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001587 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001588 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001589 const std::vector<const DexFile*>* dex_files_;
1590 ClassLinker* const class_linker_;
1591 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001592};
1593
Igor Murashkin545412b2017-08-17 15:26:54 -07001594class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001595 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001596 WriteCodeMethodVisitor(OatWriter* writer,
1597 OutputStream* out,
1598 const size_t file_offset,
1599 size_t relative_offset,
1600 OrderedMethodList ordered_methods)
1601 : OrderedMethodVisitor(std::move(ordered_methods)),
1602 writer_(writer),
1603 offset_(relative_offset),
1604 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001605 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1606 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1607 out_(out),
1608 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001609 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001610 dex_cache_(nullptr),
1611 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001612 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001613 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001614 // If we're creating the image, the address space must be ready so that we can apply patches.
1615 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001616 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001617 }
1618
Igor Murashkin545412b2017-08-17 15:26:54 -07001619 virtual bool VisitStart() OVERRIDE {
1620 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001621 }
1622
Igor Murashkin545412b2017-08-17 15:26:54 -07001623 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001624 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001625 dex_file_ = dex_file;
1626
1627 // Ordered method visiting is only for compiled methods.
1628 DCHECK(writer_->MayHaveCompiledMethods());
1629
Mathieu Chartier72041a02017-07-14 18:23:25 -07001630 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1631 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1632 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1633 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1634 DCHECK(dex_cache_ != nullptr);
1635 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001636 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001637 }
1638
1639 virtual bool VisitComplete() {
1640 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1641 if (UNLIKELY(offset_ == 0u)) {
1642 PLOG(ERROR) << "Failed to write final relative call thunks";
1643 return false;
1644 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001645 return true;
1646 }
1647
Igor Murashkin545412b2017-08-17 15:26:54 -07001648 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001649 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001650 const MethodReference& method_ref = method_data.method_reference;
1651 UpdateDexFileAndDexCache(method_ref.dex_file);
1652
1653 OatClass* oat_class = method_data.oat_class;
1654 CompiledMethod* compiled_method = method_data.compiled_method;
1655 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001656
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001657 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001658 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001659 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001660
Igor Murashkin545412b2017-08-17 15:26:54 -07001661 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1662 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1663 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001664
Igor Murashkin545412b2017-08-17 15:26:54 -07001665 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1666 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1667
1668 // Deduplicate code arrays.
1669 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1670 if (method_offsets.code_offset_ > offset_) {
1671 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1672 if (offset_ == 0u) {
1673 ReportWriteFailure("relative call thunk", method_ref);
1674 return false;
1675 }
1676 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1677 if (alignment_size != 0) {
1678 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1679 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001680 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001681 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001682 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001683 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001684 }
1685 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1686 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1687 DCHECK_EQ(method_offsets.code_offset_,
1688 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1689 << dex_file_->PrettyMethod(method_ref.index);
1690 const OatQuickMethodHeader& method_header =
1691 oat_class->method_headers_[method_offsets_index];
1692 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1693 ReportWriteFailure("method header", method_ref);
1694 return false;
1695 }
1696 writer_->size_method_header_ += sizeof(method_header);
1697 offset_ += sizeof(method_header);
1698 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001699
Igor Murashkin545412b2017-08-17 15:26:54 -07001700 if (!compiled_method->GetPatches().empty()) {
1701 patched_code_.assign(quick_code.begin(), quick_code.end());
1702 quick_code = ArrayRef<const uint8_t>(patched_code_);
1703 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1704 uint32_t literal_offset = patch.LiteralOffset();
1705 switch (patch.GetType()) {
1706 case LinkerPatch::Type::kMethodBssEntry: {
1707 uint32_t target_offset =
1708 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1709 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1710 patch,
1711 offset_ + literal_offset,
1712 target_offset);
1713 break;
1714 }
1715 case LinkerPatch::Type::kCallRelative: {
1716 // NOTE: Relative calls across oat files are not supported.
1717 uint32_t target_offset = GetTargetOffset(patch);
1718 writer_->relative_patcher_->PatchCall(&patched_code_,
1719 literal_offset,
1720 offset_ + literal_offset,
1721 target_offset);
1722 break;
1723 }
1724 case LinkerPatch::Type::kStringRelative: {
1725 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1726 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1727 patch,
1728 offset_ + literal_offset,
1729 target_offset);
1730 break;
1731 }
1732 case LinkerPatch::Type::kStringInternTable: {
1733 uint32_t target_offset = GetInternTableEntryOffset(patch);
1734 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1735 patch,
1736 offset_ + literal_offset,
1737 target_offset);
1738 break;
1739 }
1740 case LinkerPatch::Type::kStringBssEntry: {
1741 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1742 uint32_t target_offset =
1743 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1744 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1745 patch,
1746 offset_ + literal_offset,
1747 target_offset);
1748 break;
1749 }
1750 case LinkerPatch::Type::kTypeRelative: {
1751 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1752 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1753 patch,
1754 offset_ + literal_offset,
1755 target_offset);
1756 break;
1757 }
1758 case LinkerPatch::Type::kTypeClassTable: {
1759 uint32_t target_offset = GetClassTableEntryOffset(patch);
1760 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1761 patch,
1762 offset_ + literal_offset,
1763 target_offset);
1764 break;
1765 }
1766 case LinkerPatch::Type::kTypeBssEntry: {
1767 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1768 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1769 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1770 patch,
1771 offset_ + literal_offset,
1772 target_offset);
1773 break;
1774 }
1775 case LinkerPatch::Type::kCall: {
1776 uint32_t target_offset = GetTargetOffset(patch);
1777 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1778 break;
1779 }
1780 case LinkerPatch::Type::kMethodRelative: {
1781 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1782 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1783 patch,
1784 offset_ + literal_offset,
1785 target_offset);
1786 break;
1787 }
1788 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1789 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1790 patch,
1791 offset_ + literal_offset);
1792 break;
1793 }
1794 default: {
1795 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1796 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001797 }
1798 }
1799 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001800 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001801
1802 if (!out->WriteFully(quick_code.data(), code_size)) {
1803 ReportWriteFailure("method code", method_ref);
1804 return false;
1805 }
1806 writer_->size_code_ += code_size;
1807 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001808 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001809 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001810
1811 return true;
1812 }
1813
Igor Murashkin545412b2017-08-17 15:26:54 -07001814 size_t GetOffset() const {
1815 return offset_;
1816 }
1817
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001818 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001819 OatWriter* const writer_;
1820
1821 // Updated in VisitMethod as methods are written out.
1822 size_t offset_;
1823
1824 // Potentially varies with every different VisitMethod.
1825 // Used to determine which DexCache to use when finding ArtMethods.
1826 const DexFile* dex_file_;
1827
1828 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001829 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001830 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001831 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001832 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001833 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001834 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001835 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001836 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001837 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001838 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001839
Igor Murashkin545412b2017-08-17 15:26:54 -07001840 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001841 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001842 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001843 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001844
Mathieu Chartiere401d142015-04-22 13:56:20 -07001845 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001846 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001847 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001848 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001849 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1850 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001851 ArtMethod* method =
1852 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001853 CHECK(method != nullptr);
1854 return method;
1855 }
1856
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001857 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001858 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1859 // If there's no new compiled code, either we're compiling an app and the target method
1860 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001861 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001862 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001863 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001864 const void* oat_code_offset =
1865 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001866 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001867 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001868 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1869 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1870 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1871 target_offset = PointerToLowMemUInt32(oat_code_offset);
1872 } else {
1873 target_offset = target->IsNative()
1874 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1875 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1876 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001877 }
1878 return target_offset;
1879 }
1880
Vladimir Markocd556b02017-02-03 11:47:34 +00001881 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001882 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001883 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001884 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001885 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1886 }
1887
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001888 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001889 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001890 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001891 ObjPtr<mirror::Class> type =
1892 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001893 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001894 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001895 }
1896
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001897 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001898 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001899 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1900 patch.TargetStringIndex(),
Vladimir Markof25cc732017-03-16 16:18:15 +00001901 GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001902 DCHECK(string != nullptr);
1903 DCHECK(writer_->HasBootImage() ||
1904 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1905 return string;
1906 }
1907
Vladimir Marko65979462017-05-19 17:25:12 +01001908 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1909 DCHECK(writer_->HasBootImage());
1910 method = writer_->image_writer_->GetImageMethodAddress(method);
1911 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1912 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1913 // TODO: Clean up offset types. The target offset must be treated as signed.
1914 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1915 }
1916
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001917 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001918 DCHECK(writer_->HasBootImage());
1919 object = writer_->image_writer_->GetImageAddress(object);
1920 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1921 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1922 // TODO: Clean up offset types. The target offset must be treated as signed.
1923 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1924 }
1925
Vladimir Markof4da6752014-08-01 19:04:18 +01001926 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001927 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001928 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001929 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001930 } else {
1931 // NOTE: We're using linker patches for app->boot references when the image can
1932 // be relocated and therefore we need to emit .oat_patches. We're not using this
1933 // for app->app references, so check that the object is in the image space.
1934 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001935 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001936 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001937 uint32_t address = PointerToLowMemUInt32(object);
1938 DCHECK_LE(offset + 4, code->size());
1939 uint8_t* data = &(*code)[offset];
1940 data[0] = address & 0xffu;
1941 data[1] = (address >> 8) & 0xffu;
1942 data[2] = (address >> 16) & 0xffu;
1943 data[3] = (address >> 24) & 0xffu;
1944 }
1945
1946 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001947 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001948 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001949 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001950 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1951 // TODO: Clean up offset types.
1952 // The target_offset must be treated as signed for cross-oat patching.
1953 const void* target = reinterpret_cast<const void*>(
1954 writer_->image_writer_->GetOatDataBegin(oat_index) +
1955 static_cast<int32_t>(target_offset));
1956 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001957 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001958 DCHECK_LE(offset + 4, code->size());
1959 uint8_t* data = &(*code)[offset];
1960 data[0] = address & 0xffu;
1961 data[1] = (address >> 8) & 0xffu;
1962 data[2] = (address >> 16) & 0xffu;
1963 data[3] = (address >> 24) & 0xffu;
1964 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001965
1966 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
1967 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
1968 REQUIRES_SHARED(Locks::mutator_lock_) {
1969 DCHECK(!writer_->HasBootImage());
1970 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
1971 *patch.TargetStringDexFile(), patch.TargetStringIndex());
1972 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01001973 return GetBootImageTableEntryOffset(string_root);
1974 }
1975
1976 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
1977 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
1978 REQUIRES_SHARED(Locks::mutator_lock_) {
1979 DCHECK(!writer_->HasBootImage());
1980 const uint8_t* table_slot =
1981 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1982 DCHECK(table_slot != nullptr);
1983 return GetBootImageTableEntryOffset(table_slot);
1984 }
1985
1986 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001987 uint32_t base_offset = writer_->bss_start_;
1988 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1989 const uint8_t* const_tables_begin =
1990 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01001991 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001992 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
1993 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
1994 return base_offset + offset;
1995 }
1996 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
1997 }
1998 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
1999 UNREACHABLE();
2000 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002001};
2002
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002003class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2004 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002005 WriteMapMethodVisitor(OatWriter* writer,
2006 OutputStream* out,
2007 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002008 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002009 : OatDexMethodVisitor(writer, relative_offset),
2010 out_(out),
2011 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002012
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002013 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002014 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002015 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2016
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002017 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002018 size_t file_offset = file_offset_;
2019 OutputStream* out = out_;
2020
Mingyao Yang063fc772016-08-02 11:02:54 -07002021 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002022 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002023 ++method_offsets_index_;
2024
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002025 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2026 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2027 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002028 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002029
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002030 // If vdex is enabled, only emit the map for compiled code. The quickening info
2031 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002032 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002033 // Transform map_offset to actual oat data offset.
2034 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2035 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002036 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002037
2038 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2039 size_t map_size = map.size() * sizeof(map[0]);
2040 if (map_offset == offset_) {
2041 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002042 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002043 ReportWriteFailure(it);
2044 return false;
2045 }
2046 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002047 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002048 }
2049 DCHECK_OFFSET_();
2050 }
2051
2052 return true;
2053 }
2054
2055 private:
2056 OutputStream* const out_;
2057 size_t const file_offset_;
2058
2059 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002060 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002061 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002062 }
2063};
2064
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002065class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2066 public:
2067 WriteMethodInfoVisitor(OatWriter* writer,
2068 OutputStream* out,
2069 const size_t file_offset,
2070 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002071 : OatDexMethodVisitor(writer, relative_offset),
2072 out_(out),
2073 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002074
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002075 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002076 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2077 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2078
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002079 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002080 size_t file_offset = file_offset_;
2081 OutputStream* out = out_;
2082 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2083 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2084 ++method_offsets_index_;
2085 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2086 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2087 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2088 << dex_file_->PrettyMethod(it.GetMemberIndex());
2089 if (map_offset != 0u) {
2090 // Transform map_offset to actual oat data offset.
2091 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2092 DCHECK_NE(map_offset, 0u);
2093 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2094
2095 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2096 size_t map_size = map.size() * sizeof(map[0]);
2097 if (map_offset == offset_) {
2098 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2099 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2100 ReportWriteFailure(it);
2101 return false;
2102 }
2103 offset_ += map_size;
2104 }
2105 }
2106 DCHECK_OFFSET_();
2107 }
2108
2109 return true;
2110 }
2111
2112 private:
2113 OutputStream* const out_;
2114 size_t const file_offset_;
2115
2116 void ReportWriteFailure(const ClassDataItemIterator& it) {
2117 PLOG(ERROR) << "Failed to write map for "
2118 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2119 }
2120};
2121
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002122// Visit all methods from all classes in all dex files with the specified visitor.
2123bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2124 for (const DexFile* dex_file : *dex_files_) {
2125 const size_t class_def_count = dex_file->NumClassDefs();
2126 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2127 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2128 return false;
2129 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002130 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002131 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2132 const uint8_t* class_data = dex_file->GetClassData(class_def);
2133 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2134 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002135 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002136 size_t class_def_method_index = 0u;
2137 while (it.HasNextDirectMethod()) {
2138 if (!visitor->VisitMethod(class_def_method_index, it)) {
2139 return false;
2140 }
2141 ++class_def_method_index;
2142 it.Next();
2143 }
2144 while (it.HasNextVirtualMethod()) {
2145 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
2146 return false;
2147 }
2148 ++class_def_method_index;
2149 it.Next();
2150 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002151 }
2152 }
2153 if (UNLIKELY(!visitor->EndClass())) {
2154 return false;
2155 }
2156 }
2157 }
2158 return true;
2159}
2160
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002161size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2162 const InstructionSetFeatures* instruction_set_features,
2163 uint32_t num_dex_files,
2164 SafeMap<std::string, std::string>* key_value_store) {
2165 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2166 oat_header_.reset(OatHeader::Create(instruction_set,
2167 instruction_set_features,
2168 num_dex_files,
2169 key_value_store));
2170 size_oat_header_ += sizeof(OatHeader);
2171 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002172 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002173}
2174
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002175size_t OatWriter::InitClassOffsets(size_t offset) {
2176 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002177 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002178 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2179 if (!oat_dex_file.class_offsets_.empty()) {
2180 // Class offsets are required to be 4 byte aligned.
2181 offset = RoundUp(offset, 4u);
2182 oat_dex_file.class_offsets_offset_ = offset;
2183 offset += oat_dex_file.GetClassOffsetsRawSize();
2184 DCHECK_ALIGNED(offset, 4u);
2185 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002186 }
2187 return offset;
2188}
2189
Brian Carlstrom389efb02012-01-11 12:06:26 -08002190size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002191 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002192 InitOatClassesMethodVisitor visitor(this, offset);
2193 bool success = VisitDexMethods(&visitor);
2194 CHECK(success);
2195 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002196
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002197 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002198 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002199 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2200 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002201 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002202 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002203 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002204 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002205 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002206 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002207
2208 return offset;
2209}
2210
2211size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002212 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002213 return offset;
2214 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002215 {
2216 InitMapMethodVisitor visitor(this, offset);
2217 bool success = VisitDexMethods(&visitor);
2218 DCHECK(success);
2219 offset = visitor.GetOffset();
2220 }
2221 {
2222 InitMethodInfoVisitor visitor(this, offset);
2223 bool success = VisitDexMethods(&visitor);
2224 DCHECK(success);
2225 offset = visitor.GetOffset();
2226 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002227 return offset;
2228}
2229
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002230size_t OatWriter::InitMethodBssMappings(size_t offset) {
2231 size_t number_of_dex_files = 0u;
2232 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2233 const DexFile* dex_file = (*dex_files_)[i];
2234 auto it = bss_method_entry_references_.find(dex_file);
2235 if (it != bss_method_entry_references_.end()) {
2236 const BitVector& method_indexes = it->second;
2237 ++number_of_dex_files;
2238 // If there are any classes, the class offsets allocation aligns the offset
2239 // and we cannot have method bss mappings without class offsets.
2240 static_assert(alignof(MethodBssMapping) == 4u, "MethodBssMapping alignment check.");
2241 DCHECK_ALIGNED(offset, 4u);
2242 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2243
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01002244 MethodBssMappingEncoder encoder(
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002245 GetInstructionSetPointerSize(oat_header_->GetInstructionSet()));
2246 size_t number_of_entries = 0u;
2247 bool first_index = true;
2248 for (uint32_t method_index : method_indexes.Indexes()) {
2249 uint32_t bss_offset = bss_method_entries_.Get(MethodReference(dex_file, method_index));
2250 if (first_index || !encoder.TryMerge(method_index, bss_offset)) {
2251 encoder.Reset(method_index, bss_offset);
2252 ++number_of_entries;
2253 first_index = false;
2254 }
2255 }
2256 DCHECK_NE(number_of_entries, 0u);
2257 offset += MethodBssMapping::ComputeSize(number_of_entries);
2258 }
2259 }
2260 // Check that all dex files targeted by method bss entries are in `*dex_files_`.
2261 CHECK_EQ(number_of_dex_files, bss_method_entry_references_.size());
2262 return offset;
2263}
2264
2265size_t OatWriter::InitOatDexFiles(size_t offset) {
2266 // Initialize offsets of oat dex files.
2267 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2268 oat_dex_file.offset_ = offset;
2269 offset += oat_dex_file.SizeOf();
2270 }
2271 return offset;
2272}
2273
Brian Carlstrome24fa612011-09-29 00:53:55 -07002274size_t OatWriter::InitOatCode(size_t offset) {
2275 // calculate the offsets within OatHeader to executable code
2276 size_t old_offset = offset;
2277 // required to be on a new page boundary
2278 offset = RoundUp(offset, kPageSize);
2279 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002280 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002281 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2282 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2283 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002284 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002285 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002286 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2287 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002288
Vladimir Marko1b404a82017-09-01 13:35:26 +01002289 #define DO_TRAMPOLINE(field, fn_name) \
2290 offset = CompiledCode::AlignCode(offset, instruction_set); \
2291 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2292 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2293 (field) = compiler_driver_->Create ## fn_name(); \
2294 if (generate_debug_info) { \
2295 debug::MethodDebugInfo info = {}; \
2296 info.trampoline_name = #fn_name; \
2297 info.isa = instruction_set; \
2298 info.is_code_address_text_relative = true; \
2299 /* Use the code offset rather than the `adjusted_offset`. */ \
2300 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2301 info.code_size = (field)->size(); \
2302 method_info_.push_back(std::move(info)); \
2303 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002304 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002305
Ian Rogers848871b2013-08-05 10:56:33 -07002306 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002307 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002308 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002309 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2310 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002311
Ian Rogers848871b2013-08-05 10:56:33 -07002312 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002313 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002314 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002315 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002316 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002317 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002318 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002319 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002320 return offset;
2321}
2322
2323size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002324 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002325 if (kOatWriterDebugOatCodeLayout) {
2326 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2327 << this << "), "
2328 << "compilation is disabled";
2329 }
2330
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002331 return offset;
2332 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002333 bool success = false;
2334
2335 {
2336 ScopedObjectAccess soa(Thread::Current());
2337
2338 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2339 success = VisitDexMethods(&layout_code_visitor);
2340 DCHECK(success);
2341
2342 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2343 this,
2344 offset,
2345 layout_code_visitor.ReleaseOrderedMethods());
2346 success = layout_reserve_code_visitor.Visit();
2347 DCHECK(success);
2348 offset = layout_reserve_code_visitor.GetOffset();
2349
2350 // Save the method order because the WriteCodeMethodVisitor will need this
2351 // order again.
2352 DCHECK(ordered_methods_ == nullptr);
2353 ordered_methods_.reset(
2354 new OrderedMethodList(
2355 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2356
2357 if (kOatWriterDebugOatCodeLayout) {
2358 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2359 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2360 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2361 LOG(INFO) << pretty_name
2362 << "@ offset "
2363 << relative_patcher_->GetOffset(ordered_method.method_reference)
2364 << " X hotness "
2365 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2366 }
2367 }
2368 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002369
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002370 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002371 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002372 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002373 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002374 DCHECK(success);
2375 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002376 }
Logan Chien8b977d32012-02-21 19:14:55 +08002377
Brian Carlstrome24fa612011-09-29 00:53:55 -07002378 return offset;
2379}
2380
Vladimir Markoaad75c62016-10-03 08:46:48 +00002381void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002382 {
2383 InitBssLayoutMethodVisitor visitor(this);
2384 bool success = VisitDexMethods(&visitor);
2385 DCHECK(success);
2386 }
2387
2388 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002389 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002390 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002391 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002392 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002393 if (!map_boot_image_tables_to_bss_ &&
2394 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002395 bss_type_entries_.empty() &&
2396 bss_string_entries_.empty()) {
2397 // Nothing to put to the .bss section.
2398 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002399 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002400
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002401 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002402 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002403 if (map_boot_image_tables_to_bss_) {
2404 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2405 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2406 }
2407 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002408
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002409 bss_methods_offset_ = bss_size_;
2410
2411 // Prepare offsets for .bss ArtMethod entries.
2412 for (auto& entry : bss_method_entries_) {
2413 DCHECK_EQ(entry.second, 0u);
2414 entry.second = bss_size_;
2415 bss_size_ += static_cast<size_t>(pointer_size);
2416 }
2417
Vladimir Markoaad75c62016-10-03 08:46:48 +00002418 bss_roots_offset_ = bss_size_;
2419
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002420 // Prepare offsets for .bss Class entries.
2421 for (auto& entry : bss_type_entries_) {
2422 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002423 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002424 bss_size_ += sizeof(GcRoot<mirror::Class>);
2425 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002426 // Prepare offsets for .bss String entries.
2427 for (auto& entry : bss_string_entries_) {
2428 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002429 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002430 bss_size_ += sizeof(GcRoot<mirror::String>);
2431 }
2432}
2433
David Srbeckybc90fd02015-04-22 19:40:27 +01002434bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002435 CHECK(write_state_ == WriteState::kWriteRoData);
2436
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002437 size_t file_offset = oat_data_offset_;
2438 off_t current_offset = out->Seek(0, kSeekCurrent);
2439 if (current_offset == static_cast<off_t>(-1)) {
2440 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2441 }
2442 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2443 size_t relative_offset = current_offset - file_offset;
2444
Vladimir Markoe079e212016-05-25 12:49:49 +01002445 // Wrap out to update checksum with each write.
2446 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2447 out = &checksum_updating_out;
2448
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002449 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2450 if (relative_offset == 0) {
2451 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002452 return false;
2453 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002454
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002455 relative_offset = WriteClasses(out, file_offset, relative_offset);
2456 if (relative_offset == 0) {
2457 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002458 return false;
2459 }
2460
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002461 relative_offset = WriteMethodBssMappings(out, file_offset, relative_offset);
2462 if (relative_offset == 0) {
2463 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002464 return false;
2465 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002466
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002467 relative_offset = WriteMaps(out, file_offset, relative_offset);
2468 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002469 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2470 return false;
2471 }
2472
2473 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2474 if (relative_offset == 0) {
2475 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002476 return false;
2477 }
2478
David Srbeckybc90fd02015-04-22 19:40:27 +01002479 // Write padding.
2480 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2481 relative_offset += size_executable_offset_alignment_;
2482 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2483 size_t expected_file_offset = file_offset + relative_offset;
2484 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2485 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2486 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2487 return 0;
2488 }
2489 DCHECK_OFFSET();
2490
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002491 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002492 return true;
2493}
2494
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002495class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
2496 public:
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002497 WriteQuickeningInfoMethodVisitor(OatWriter* writer,
2498 OutputStream* out,
2499 uint32_t offset,
2500 SafeMap<const uint8_t*, uint32_t>* offset_map)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002501 : DexMethodVisitor(writer, offset),
2502 out_(out),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002503 written_bytes_(0u),
2504 offset_map_(offset_map) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002505
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002506 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it)
2507 OVERRIDE {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002508 uint32_t method_idx = it.GetMemberIndex();
2509 CompiledMethod* compiled_method =
2510 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
2511
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002512 if (HasQuickeningInfo(compiled_method)) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002513 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002514 // Deduplication is already done on a pointer basis by the compiler driver,
2515 // so we can simply compare the pointers to find out if things are duplicated.
2516 if (offset_map_->find(map.data()) == offset_map_->end()) {
2517 uint32_t length = map.size() * sizeof(map.front());
2518 offset_map_->Put(map.data(), written_bytes_);
2519 if (!out_->WriteFully(&length, sizeof(length)) ||
2520 !out_->WriteFully(map.data(), length)) {
2521 PLOG(ERROR) << "Failed to write quickening info for "
2522 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to "
2523 << out_->GetLocation();
2524 return false;
2525 }
2526 written_bytes_ += sizeof(length) + length;
2527 offset_ += sizeof(length) + length;
2528 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002529 }
2530
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002531 return true;
2532 }
2533
2534 size_t GetNumberOfWrittenBytes() const {
2535 return written_bytes_;
2536 }
2537
2538 private:
2539 OutputStream* const out_;
2540 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002541 // Maps quickening map to its offset in the file.
2542 SafeMap<const uint8_t*, uint32_t>* offset_map_;
2543};
2544
2545class OatWriter::WriteQuickeningIndicesMethodVisitor {
2546 public:
2547 WriteQuickeningIndicesMethodVisitor(OutputStream* out,
2548 uint32_t indices_offset,
2549 const SafeMap<const uint8_t*, uint32_t>& offset_map,
2550 std::vector<uint32_t>* dex_files_offset)
2551 : out_(out),
2552 indices_offset_(indices_offset),
2553 written_bytes_(0u),
2554 dex_files_offset_(dex_files_offset),
2555 offset_map_(offset_map) {}
2556
2557 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files, const CompilerDriver& driver) {
2558 for (const DexFile* dex_file : dex_files) {
2559 // Record the offset for this current dex file. It will be written in the vdex file
2560 // later.
2561 dex_files_offset_->push_back(indices_offset_ + GetNumberOfWrittenBytes());
2562 const size_t class_def_count = dex_file->NumClassDefs();
2563 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2564 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2565 const uint8_t* class_data = dex_file->GetClassData(class_def);
2566 if (class_data == nullptr) {
2567 continue;
2568 }
2569 for (ClassDataItemIterator class_it(*dex_file, class_data);
2570 class_it.HasNext();
2571 class_it.Next()) {
2572 if (!class_it.IsAtMethod()) {
2573 continue;
2574 }
2575 uint32_t method_idx = class_it.GetMemberIndex();
2576 CompiledMethod* compiled_method =
2577 driver.GetCompiledMethod(MethodReference(dex_file, method_idx));
2578 if (HasQuickeningInfo(compiled_method)) {
2579 uint32_t code_item_offset = class_it.GetMethodCodeItemOffset();
2580 uint32_t offset = offset_map_.Get(compiled_method->GetVmapTable().data());
2581 if (!out_->WriteFully(&code_item_offset, sizeof(code_item_offset)) ||
2582 !out_->WriteFully(&offset, sizeof(offset))) {
2583 PLOG(ERROR) << "Failed to write quickening info for "
2584 << dex_file->PrettyMethod(method_idx) << " to "
2585 << out_->GetLocation();
2586 return false;
2587 }
2588 written_bytes_ += sizeof(code_item_offset) + sizeof(offset);
2589 }
2590 }
2591 }
2592 }
2593 return true;
2594 }
2595
2596 size_t GetNumberOfWrittenBytes() const {
2597 return written_bytes_;
2598 }
2599
2600 private:
2601 OutputStream* const out_;
2602 const uint32_t indices_offset_;
2603 size_t written_bytes_;
2604 std::vector<uint32_t>* dex_files_offset_;
2605 // Maps quickening map to its offset in the file.
2606 const SafeMap<const uint8_t*, uint32_t>& offset_map_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002607};
2608
2609bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
2610 if (!kIsVdexEnabled) {
2611 return true;
2612 }
2613
2614 size_t initial_offset = vdex_size_;
2615 size_t start_offset = RoundUp(initial_offset, 4u);
2616
2617 vdex_size_ = start_offset;
2618 vdex_quickening_info_offset_ = vdex_size_;
2619 size_quickening_info_alignment_ = start_offset - initial_offset;
2620
2621 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2622 if (actual_offset != static_cast<off_t>(start_offset)) {
2623 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2624 << " Expected: " << start_offset
2625 << " Output: " << vdex_out->GetLocation();
2626 return false;
2627 }
2628
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002629 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002630 std::vector<uint32_t> dex_files_indices;
2631 SafeMap<const uint8_t*, uint32_t> offset_map;
2632 WriteQuickeningInfoMethodVisitor visitor1(this, vdex_out, start_offset, &offset_map);
2633 if (!VisitDexMethods(&visitor1)) {
2634 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2635 return false;
2636 }
2637
2638 WriteQuickeningIndicesMethodVisitor visitor2(vdex_out,
2639 visitor1.GetNumberOfWrittenBytes(),
2640 offset_map,
2641 &dex_files_indices);
2642 if (!visitor2.VisitDexMethods(*dex_files_, *compiler_driver_)) {
2643 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2644 return false;
2645 }
2646
2647 DCHECK_EQ(dex_files_->size(), dex_files_indices.size());
2648 if (!vdex_out->WriteFully(
2649 dex_files_indices.data(), sizeof(dex_files_indices[0]) * dex_files_indices.size())) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002650 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2651 return false;
2652 }
2653
2654 if (!vdex_out->Flush()) {
2655 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2656 << " File: " << vdex_out->GetLocation();
2657 return false;
2658 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002659 size_quickening_info_ = visitor1.GetNumberOfWrittenBytes() +
2660 visitor2.GetNumberOfWrittenBytes() +
2661 dex_files_->size() * sizeof(uint32_t);
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002662 } else {
2663 // We know we did not quicken.
2664 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002665 }
2666
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002667 vdex_size_ += size_quickening_info_;
2668 return true;
2669}
2670
David Brazdil5d5a36b2016-09-14 15:34:10 +01002671bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
2672 if (!kIsVdexEnabled) {
2673 return true;
2674 }
2675
2676 if (verifier_deps == nullptr) {
2677 // Nothing to write. Record the offset, but no need
2678 // for alignment.
2679 vdex_verifier_deps_offset_ = vdex_size_;
2680 return true;
2681 }
2682
2683 size_t initial_offset = vdex_size_;
2684 size_t start_offset = RoundUp(initial_offset, 4u);
2685
2686 vdex_size_ = start_offset;
2687 vdex_verifier_deps_offset_ = vdex_size_;
2688 size_verifier_deps_alignment_ = start_offset - initial_offset;
2689
2690 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2691 if (actual_offset != static_cast<off_t>(start_offset)) {
2692 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2693 << " Expected: " << start_offset
2694 << " Output: " << vdex_out->GetLocation();
2695 return false;
2696 }
2697
2698 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002699 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002700
2701 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2702 PLOG(ERROR) << "Failed to write verifier deps."
2703 << " File: " << vdex_out->GetLocation();
2704 return false;
2705 }
2706 if (!vdex_out->Flush()) {
2707 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2708 << " File: " << vdex_out->GetLocation();
2709 return false;
2710 }
2711
2712 size_verifier_deps_ = buffer.size();
2713 vdex_size_ += size_verifier_deps_;
2714 return true;
2715}
2716
David Srbeckybc90fd02015-04-22 19:40:27 +01002717bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002718 CHECK(write_state_ == WriteState::kWriteText);
2719
Vladimir Markoe079e212016-05-25 12:49:49 +01002720 // Wrap out to update checksum with each write.
2721 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2722 out = &checksum_updating_out;
2723
Vladimir Marko944da602016-02-19 12:27:55 +00002724 SetMultiOatRelativePatcherAdjustment();
2725
David Srbeckybc90fd02015-04-22 19:40:27 +01002726 const size_t file_offset = oat_data_offset_;
2727 size_t relative_offset = oat_header_->GetExecutableOffset();
2728 DCHECK_OFFSET();
2729
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002730 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002731 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002732 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002733 return false;
2734 }
2735
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002736 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2737 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002738 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002739 return false;
2740 }
2741
Vladimir Markof4da6752014-08-01 19:04:18 +01002742 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002743 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002744 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2745 return false;
2746 }
2747
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002748 if (kIsDebugBuild) {
2749 uint32_t size_total = 0;
2750 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002751 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2752 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002753
David Brazdil7b49e6c2016-09-01 11:06:18 +01002754 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002755 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002756 DO_STAT(size_dex_file_alignment_);
2757 DO_STAT(size_executable_offset_alignment_);
2758 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002759 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002760 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002761 DO_STAT(size_verifier_deps_);
2762 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002763 DO_STAT(size_quickening_info_);
2764 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002765 DO_STAT(size_interpreter_to_interpreter_bridge_);
2766 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2767 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002768 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002769 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002770 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002771 DO_STAT(size_quick_to_interpreter_bridge_);
2772 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002773 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002774 DO_STAT(size_code_);
2775 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002776 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002777 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002778 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002779 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002780 DO_STAT(size_oat_dex_file_location_size_);
2781 DO_STAT(size_oat_dex_file_location_data_);
2782 DO_STAT(size_oat_dex_file_location_checksum_);
2783 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002784 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002785 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002786 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2787 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2788 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002789 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002790 DO_STAT(size_oat_lookup_table_alignment_);
2791 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002792 DO_STAT(size_oat_class_offsets_alignment_);
2793 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002794 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002795 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002796 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002797 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002798 DO_STAT(size_method_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002799 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002800
David Brazdil7b49e6c2016-09-01 11:06:18 +01002801 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2802
2803 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2804 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002805 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002806
David Brazdil7b49e6c2016-09-01 11:06:18 +01002807 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2808 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002809
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002810 write_state_ = WriteState::kWriteHeader;
2811 return true;
2812}
2813
2814bool OatWriter::WriteHeader(OutputStream* out,
2815 uint32_t image_file_location_oat_checksum,
2816 uintptr_t image_file_location_oat_begin,
2817 int32_t image_patch_delta) {
2818 CHECK(write_state_ == WriteState::kWriteHeader);
2819
2820 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2821 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002822 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002823 CHECK_EQ(image_patch_delta, 0);
2824 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2825 } else {
2826 CHECK_ALIGNED(image_patch_delta, kPageSize);
2827 oat_header_->SetImagePatchDelta(image_patch_delta);
2828 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002829 oat_header_->UpdateChecksumWithHeaderData();
2830
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002831 const size_t file_offset = oat_data_offset_;
2832
2833 off_t current_offset = out->Seek(0, kSeekCurrent);
2834 if (current_offset == static_cast<off_t>(-1)) {
2835 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2836 return false;
2837 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002838 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002839 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2840 return false;
2841 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002842 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002843
2844 // Flush all other data before writing the header.
2845 if (!out->Flush()) {
2846 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2847 return false;
2848 }
2849 // Write the header.
2850 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002851 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002852 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2853 return false;
2854 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002855 // Flush the header data.
2856 if (!out->Flush()) {
2857 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002858 return false;
2859 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002860
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002861 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2862 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2863 return false;
2864 }
2865 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2866
2867 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002868 return true;
2869}
2870
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002871size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002872 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2873 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002874 // Class offsets are required to be 4 byte aligned.
2875 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
2876 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
2877 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
2878 return 0u;
2879 }
2880 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00002881 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002882 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002883 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002884 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002885 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002886 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002887 }
2888 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002889 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002890}
2891
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002892size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002893 const bool may_have_compiled = MayHaveCompiledMethods();
2894 if (may_have_compiled) {
2895 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
2896 }
2897 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002898 // If there are any classes, the class offsets allocation aligns the offset.
2899 DCHECK_ALIGNED(relative_offset, 4u);
2900 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002901 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002902 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00002903 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002904 relative_offset += oat_class_headers_[i].SizeOf();
2905 if (may_have_compiled) {
2906 if (!oat_classes_[i].Write(this, out)) {
2907 return 0u;
2908 }
2909 relative_offset += oat_classes_[i].SizeOf();
2910 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002911 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002912 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002913}
2914
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002915size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002916 {
2917 size_t vmap_tables_offset = relative_offset;
2918 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2919 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2920 return 0;
2921 }
2922 relative_offset = visitor.GetOffset();
2923 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002924 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002925 {
2926 size_t method_infos_offset = relative_offset;
2927 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
2928 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2929 return 0;
2930 }
2931 relative_offset = visitor.GetOffset();
2932 size_method_info_ = relative_offset - method_infos_offset;
2933 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002934
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002935 return relative_offset;
2936}
2937
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002938size_t OatWriter::WriteMethodBssMappings(OutputStream* out,
2939 size_t file_offset,
2940 size_t relative_offset) {
2941 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
2942
2943 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2944 const DexFile* dex_file = (*dex_files_)[i];
2945 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2946 auto it = bss_method_entry_references_.find(dex_file);
2947 if (it != bss_method_entry_references_.end()) {
2948 const BitVector& method_indexes = it->second;
2949 // If there are any classes, the class offsets allocation aligns the offset
2950 // and we cannot have method bss mappings without class offsets.
2951 static_assert(alignof(MethodBssMapping) == sizeof(uint32_t),
2952 "MethodBssMapping alignment check.");
2953 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
2954
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01002955 MethodBssMappingEncoder encoder(
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002956 GetInstructionSetPointerSize(oat_header_->GetInstructionSet()));
2957 // Allocate a sufficiently large MethodBssMapping.
2958 size_t number_of_method_indexes = method_indexes.NumSetBits();
2959 DCHECK_NE(number_of_method_indexes, 0u);
2960 size_t max_mappings_size = MethodBssMapping::ComputeSize(number_of_method_indexes);
2961 DCHECK_ALIGNED(max_mappings_size, sizeof(uint32_t));
2962 std::unique_ptr<uint32_t[]> storage(new uint32_t[max_mappings_size / sizeof(uint32_t)]);
2963 MethodBssMapping* mappings = new(storage.get()) MethodBssMapping(number_of_method_indexes);
2964 mappings->ClearPadding();
2965 // Encode the MethodBssMapping.
2966 auto init_it = mappings->begin();
2967 bool first_index = true;
2968 for (uint32_t method_index : method_indexes.Indexes()) {
2969 size_t bss_offset = bss_method_entries_.Get(MethodReference(dex_file, method_index));
2970 if (first_index) {
2971 first_index = false;
2972 encoder.Reset(method_index, bss_offset);
2973 } else if (!encoder.TryMerge(method_index, bss_offset)) {
2974 *init_it = encoder.GetEntry();
2975 ++init_it;
2976 encoder.Reset(method_index, bss_offset);
2977 }
2978 }
2979 // Store the last entry and shrink the mapping to the actual size.
2980 *init_it = encoder.GetEntry();
2981 ++init_it;
2982 DCHECK(init_it <= mappings->end());
2983 mappings->SetSize(std::distance(mappings->begin(), init_it));
2984 size_t mappings_size = MethodBssMapping::ComputeSize(mappings->size());
2985
2986 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
2987 DCHECK_OFFSET();
2988 if (!out->WriteFully(storage.get(), mappings_size)) {
2989 return 0u;
2990 }
2991 size_method_bss_mappings_ += mappings_size;
2992 relative_offset += mappings_size;
2993 } else {
2994 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
2995 }
2996 }
2997 return relative_offset;
2998}
2999
3000size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3001 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3002
3003 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3004 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3005 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3006 DCHECK_OFFSET();
3007
3008 // Write OatDexFile.
3009 if (!oat_dex_file->Write(this, out)) {
3010 return 0u;
3011 }
3012 relative_offset += oat_dex_file->SizeOf();
3013 }
3014
3015 return relative_offset;
3016}
3017
3018size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003019 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003020 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003021
Ian Rogers848871b2013-08-05 10:56:33 -07003022 #define DO_TRAMPOLINE(field) \
3023 do { \
3024 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3025 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003026 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003027 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003028 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003029 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003030 return false; \
3031 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003032 size_ ## field += (field)->size(); \
3033 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003034 DCHECK_OFFSET(); \
3035 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003036
Ian Rogers848871b2013-08-05 10:56:33 -07003037 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003038 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003039 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003040 DO_TRAMPOLINE(quick_resolution_trampoline_);
3041 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3042 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003043 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003044 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003045}
3046
Ian Rogers3d504072014-03-01 09:16:49 -08003047size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003048 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003049 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003050 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3051 // As with InitOatCodeDexFiles, also skip the writer if
3052 // compilation was disabled.
3053 if (kOatWriterDebugOatCodeLayout) {
3054 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3055 << this << "), "
3056 << "compilation is disabled";
3057 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003058
Igor Murashkin545412b2017-08-17 15:26:54 -07003059 return relative_offset;
3060 }
3061 ScopedObjectAccess soa(Thread::Current());
3062 DCHECK(ordered_methods_ != nullptr);
3063 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3064 std::move(ordered_methods_);
3065 WriteCodeMethodVisitor visitor(this,
3066 out,
3067 file_offset,
3068 relative_offset,
3069 std::move(*ordered_methods_ptr));
3070 if (UNLIKELY(!visitor.Visit())) {
3071 return 0;
3072 }
3073 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003074
Vladimir Markob163bb72015-03-31 21:49:49 +01003075 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3076 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3077 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3078
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003079 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003080}
3081
Vladimir Marko944da602016-02-19 12:27:55 +00003082bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003083 // Get the elf file offset of the oat file.
3084 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3085 if (raw_file_offset == static_cast<off_t>(-1)) {
3086 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3087 return false;
3088 }
3089 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3090 return true;
3091}
3092
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003093bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
3094 // Read the dex file header and perform minimal verification.
3095 uint8_t raw_header[sizeof(DexFile::Header)];
3096 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
3097 PLOG(ERROR) << "Failed to read dex file header. Actual: "
3098 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3099 return false;
3100 }
3101 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
3102 return false;
3103 }
3104
3105 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
3106 oat_dex_file->dex_file_size_ = header->file_size_;
3107 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
3108 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
3109 return true;
3110}
3111
3112bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
Mathieu Chartier292567e2017-10-12 13:24:38 -07003113 const bool valid_standard_dex_magic = StandardDexFile::IsMagicValid(raw_header);
3114 if (!valid_standard_dex_magic) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003115 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
3116 return false;
3117 }
Mathieu Chartier292567e2017-10-12 13:24:38 -07003118 if (!StandardDexFile::IsVersionValid(raw_header)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003119 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
3120 return false;
3121 }
3122 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
3123 if (header->file_size_ < sizeof(DexFile::Header)) {
3124 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
3125 << " File: " << location;
3126 return false;
3127 }
3128 return true;
3129}
3130
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003131bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003132 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003133
David Brazdil7b49e6c2016-09-01 11:06:18 +01003134 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003135
3136 // Write dex files.
3137 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003138 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003139 return false;
3140 }
3141 }
3142
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003143 CloseSources();
3144 return true;
3145}
3146
3147void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003148 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3149 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3150 }
3151 zipped_dex_files_.clear();
3152 zip_archives_.clear();
3153 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003154}
3155
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003156bool OatWriter::WriteDexFile(OutputStream* out,
3157 File* file,
3158 OatDexFile* oat_dex_file,
3159 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003160 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003161 return false;
3162 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003163 if (profile_compilation_info_ != nullptr) {
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01003164 CHECK(!update_input_vdex) << "We should never update the input vdex when doing dexlayout";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003165 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3166 return false;
3167 }
3168 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003169 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003170 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003171 return false;
3172 }
3173 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003174 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003175 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003176 return false;
3177 }
3178 } else {
3179 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003180 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003181 return false;
3182 }
3183 }
3184
3185 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003186 if (kIsVdexEnabled) {
3187 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3188 vdex_size_ += oat_dex_file->dex_file_size_;
3189 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003190 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003191 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
3192 oat_size_ += oat_dex_file->dex_file_size_;
3193 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003194 size_dex_file_ += oat_dex_file->dex_file_size_;
3195 return true;
3196}
3197
3198bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3199 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003200 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
3201 size_t start_offset = RoundUp(initial_offset, 4);
3202 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
3203 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003204
3205 // Seek to the start of the dex file and flush any pending operations in the stream.
3206 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003207 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3208 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003209 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003210 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003211 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3212 return false;
3213 }
3214 if (!out->Flush()) {
3215 PLOG(ERROR) << "Failed to flush before writing dex file."
3216 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3217 return false;
3218 }
3219 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003220 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003221 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003222 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003223 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3224 return false;
3225 }
3226
David Brazdil7b49e6c2016-09-01 11:06:18 +01003227 if (kIsVdexEnabled) {
3228 vdex_size_ = start_offset;
3229 } else {
3230 oat_size_ = start_offset;
3231 }
3232 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003233 return true;
3234}
3235
Jeff Hao608f2ce2016-10-19 11:17:11 -07003236bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3237 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3238 std::string error_msg;
3239 std::string location(oat_dex_file->GetLocation());
3240 std::unique_ptr<const DexFile> dex_file;
3241 if (oat_dex_file->source_.IsZipEntry()) {
3242 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3243 std::unique_ptr<MemMap> mem_map(
3244 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003245 if (mem_map == nullptr) {
3246 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3247 return false;
3248 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003249 dex_file = DexFileLoader::Open(location,
3250 zip_entry->GetCrc32(),
3251 std::move(mem_map),
3252 /* verify */ true,
3253 /* verify_checksum */ true,
3254 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003255 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003256 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003257 int dup_fd = dup(raw_file->Fd());
3258 if (dup_fd < 0) {
3259 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3260 return false;
3261 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003262 dex_file = DexFileLoader::OpenDex(dup_fd, location, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003263 } else {
3264 // The source data is a vdex file.
3265 CHECK(oat_dex_file->source_.IsRawData())
3266 << static_cast<size_t>(oat_dex_file->source_.GetType());
3267 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3268 // Note: The raw data has already been checked to contain the header
3269 // and all the data that the header specifies as the file size.
3270 DCHECK(raw_dex_file != nullptr);
3271 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3272 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3273 // Since the source may have had its layout changed, or may be quickened, don't verify it.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003274 dex_file = DexFileLoader::Open(raw_dex_file,
3275 header->file_size_,
3276 location,
3277 oat_dex_file->dex_file_location_checksum_,
3278 nullptr,
3279 /* verify */ false,
3280 /* verify_checksum */ false,
3281 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003282 }
Jeff Haode197542017-02-03 10:48:13 -08003283 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003284 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003285 return false;
3286 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003287 Options options;
3288 options.output_to_memmap_ = true;
3289 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
3290 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
3291 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003292 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003293 return false;
3294 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07003295 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
Jeff Hao608f2ce2016-10-19 11:17:11 -07003296 // Set the checksum of the new oat dex file to be the original file's checksum.
3297 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
3298 return true;
3299}
3300
David Brazdil7b49e6c2016-09-01 11:06:18 +01003301bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003302 File* file,
3303 OatDexFile* oat_dex_file,
3304 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003305 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
3306 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003307
3308 // Extract the dex file and get the extracted size.
3309 std::string error_msg;
3310 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3311 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3312 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3313 return false;
3314 }
3315 if (file->Flush() != 0) {
3316 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3317 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3318 return false;
3319 }
3320 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3321 if (extracted_end == static_cast<off_t>(-1)) {
3322 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3323 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3324 return false;
3325 }
3326 if (extracted_end < static_cast<off_t>(start_offset)) {
3327 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3328 << " Start: " << start_offset
3329 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3330 return false;
3331 }
3332 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3333 if (extracted_size < sizeof(DexFile::Header)) {
3334 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3335 << extracted_size << " File: " << oat_dex_file->GetLocation();
3336 return false;
3337 }
3338
3339 // Read the dex file header and extract required data to OatDexFile.
3340 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3341 if (actual_offset != static_cast<off_t>(start_offset)) {
3342 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3343 << " Expected: " << start_offset
3344 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3345 return false;
3346 }
3347 if (!ReadDexFileHeader(file, oat_dex_file)) {
3348 return false;
3349 }
3350 if (extracted_size < oat_dex_file->dex_file_size_) {
3351 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3352 << " file size from header: " << oat_dex_file->dex_file_size_
3353 << " File: " << oat_dex_file->GetLocation();
3354 return false;
3355 }
3356
3357 // Override the checksum from header with the CRC from ZIP entry.
3358 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
3359
3360 // Seek both file and stream to the end offset.
3361 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3362 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3363 if (actual_offset != static_cast<off_t>(end_offset)) {
3364 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3365 << " Expected: " << end_offset
3366 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3367 return false;
3368 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003369 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003370 if (actual_offset != static_cast<off_t>(end_offset)) {
3371 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3372 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3373 return false;
3374 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003375 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003376 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3377 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3378 return false;
3379 }
3380
3381 // If we extracted more than the size specified in the header, truncate the file.
3382 if (extracted_size > oat_dex_file->dex_file_size_) {
3383 if (file->SetLength(end_offset) != 0) {
3384 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003385 << " File: " << oat_dex_file->GetLocation()
3386 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003387 return false;
3388 }
3389 }
3390
3391 return true;
3392}
3393
David Brazdil7b49e6c2016-09-01 11:06:18 +01003394bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003395 File* file,
3396 OatDexFile* oat_dex_file,
3397 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003398 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
3399 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003400
3401 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3402 if (input_offset != static_cast<off_t>(0)) {
3403 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3404 << " Expected: 0"
3405 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3406 return false;
3407 }
3408 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
3409 return false;
3410 }
3411
3412 // Copy the input dex file using sendfile().
3413 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3414 PLOG(ERROR) << "Failed to copy dex file to oat file."
3415 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3416 return false;
3417 }
3418 if (file->Flush() != 0) {
3419 PLOG(ERROR) << "Failed to flush dex file."
3420 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3421 return false;
3422 }
3423
3424 // Check file position and seek the stream to the end offset.
3425 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3426 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3427 if (actual_offset != static_cast<off_t>(end_offset)) {
3428 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3429 << " Expected: " << end_offset
3430 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3431 return false;
3432 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003433 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003434 if (actual_offset != static_cast<off_t>(end_offset)) {
3435 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3436 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3437 return false;
3438 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003439 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003440 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3441 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3442 return false;
3443 }
3444
3445 return true;
3446}
3447
David Brazdil7b49e6c2016-09-01 11:06:18 +01003448bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003449 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003450 const uint8_t* dex_file,
3451 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003452 // Note: The raw data has already been checked to contain the header
3453 // and all the data that the header specifies as the file size.
3454 DCHECK(dex_file != nullptr);
3455 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3456 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3457
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003458 if (update_input_vdex) {
3459 // The vdex already contains the dex code, no need to write it again.
3460 } else {
3461 if (!out->WriteFully(dex_file, header->file_size_)) {
3462 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3463 << " to " << out->GetLocation();
3464 return false;
3465 }
3466 if (!out->Flush()) {
3467 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3468 << " File: " << oat_dex_file->GetLocation();
3469 return false;
3470 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003471 }
3472
3473 // Update dex file size and resize class offsets in the OatDexFile.
3474 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003475 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003476 oat_dex_file->dex_file_size_ = header->file_size_;
3477 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
3478 return true;
3479}
3480
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003481bool OatWriter::OpenDexFiles(
3482 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003483 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003484 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
3485 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3486 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3487
3488 if (oat_dex_files_.empty()) {
3489 // Nothing to do.
3490 return true;
3491 }
3492
3493 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003494 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
3495
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003496 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003497 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3498 length,
3499 PROT_READ | PROT_WRITE,
3500 MAP_SHARED,
3501 file->Fd(),
3502 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
3503 /* low_4gb */ false,
3504 file->GetPath().c_str(),
3505 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003506 if (dex_files_map == nullptr) {
3507 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3508 << " error: " << error_msg;
3509 return false;
3510 }
3511 std::vector<std::unique_ptr<const DexFile>> dex_files;
3512 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3513 // Make sure no one messed with input files while we were copying data.
3514 // At the very least we need consistent file size and number of class definitions.
3515 const uint8_t* raw_dex_file =
3516 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
3517 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
3518 // Note: ValidateDexFileHeader() already logged an error message.
3519 LOG(ERROR) << "Failed to verify written dex file header!"
3520 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3521 << " ~ " << static_cast<const void*>(raw_dex_file);
3522 return false;
3523 }
3524 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3525 if (header->file_size_ != oat_dex_file.dex_file_size_) {
3526 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
3527 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3528 << " Output: " << file->GetPath();
3529 return false;
3530 }
3531 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
3532 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
3533 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
3534 << " Output: " << file->GetPath();
3535 return false;
3536 }
3537
3538 // Now, open the dex file.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003539 dex_files.emplace_back(DexFileLoader::Open(raw_dex_file,
3540 oat_dex_file.dex_file_size_,
3541 oat_dex_file.GetLocation(),
3542 oat_dex_file.dex_file_location_checksum_,
3543 /* oat_dex_file */ nullptr,
3544 verify,
3545 verify,
3546 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003547 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003548 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3549 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003550 return false;
3551 }
3552 }
3553
3554 *opened_dex_files_map = std::move(dex_files_map);
3555 *opened_dex_files = std::move(dex_files);
3556 return true;
3557}
3558
3559bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003560 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003561 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3562 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3563
David Brazdil7b49e6c2016-09-01 11:06:18 +01003564 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3565 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3566 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3567 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3568 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3569 return false;
3570 }
3571
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003572 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3573 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3574 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003575 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3576
3577 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3578 oat_dex_file->class_offsets_.empty()) {
3579 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003580 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003581
3582 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3583 if (table_size == 0u) {
3584 continue;
3585 }
3586
3587 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003588 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003589 const DexFile& dex_file = *opened_dex_files[i];
3590 {
3591 std::unique_ptr<TypeLookupTable> type_lookup_table =
3592 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3593 type_lookup_table_oat_dex_files_.push_back(
3594 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3595 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3596 }
3597 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003598
3599 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003600 size_t initial_offset = oat_size_;
3601 size_t rodata_offset = RoundUp(initial_offset, 4);
3602 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003603
3604 if (padding_size != 0u) {
3605 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003606 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003607 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3608 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003609 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003610 return false;
3611 }
3612 }
3613
3614 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003615 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003616 DCHECK_EQ(table_size, table->RawDataLength());
3617
David Brazdil7b49e6c2016-09-01 11:06:18 +01003618 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003619 PLOG(ERROR) << "Failed to write lookup table."
3620 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003621 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003622 return false;
3623 }
3624
3625 oat_dex_file->lookup_table_offset_ = rodata_offset;
3626
David Brazdil7b49e6c2016-09-01 11:06:18 +01003627 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003628 size_oat_lookup_table_ += table_size;
3629 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003630 }
3631
David Brazdil7b49e6c2016-09-01 11:06:18 +01003632 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003633 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003634 << " File: " << oat_rodata->GetLocation();
3635 return false;
3636 }
3637
3638 return true;
3639}
3640
Mathieu Chartier120aa282017-08-05 16:03:03 -07003641bool OatWriter::WriteDexLayoutSections(
3642 OutputStream* oat_rodata,
3643 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3644 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3645
3646 if (!kWriteDexLayoutInfo) {
3647 return true;;
3648 }
3649
3650 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3651 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3652 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3653 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3654 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3655 return false;
3656 }
3657
3658 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3659 size_t rodata_offset = oat_size_;
3660 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3661 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3662 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3663
3664 // Write dex layout section alignment bytes.
3665 const size_t padding_size =
3666 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3667 if (padding_size != 0u) {
3668 std::vector<uint8_t> buffer(padding_size, 0u);
3669 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3670 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3671 << " File: " << oat_dex_file->GetLocation()
3672 << " Output: " << oat_rodata->GetLocation();
3673 return false;
3674 }
3675 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3676 rodata_offset += padding_size;
3677 }
3678
3679 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3680 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3681 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3682 DCHECK(oat_dex_file != nullptr);
3683 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3684 sizeof(oat_dex_file->dex_sections_layout_))) {
3685 PLOG(ERROR) << "Failed to write dex layout sections."
3686 << " File: " << oat_dex_file->GetLocation()
3687 << " Output: " << oat_rodata->GetLocation();
3688 return false;
3689 }
3690 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3691 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3692 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3693 }
3694 oat_size_ = rodata_offset;
3695
3696 if (!oat_rodata->Flush()) {
3697 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3698 << " File: " << oat_rodata->GetLocation();
3699 return false;
3700 }
3701
3702 return true;
3703}
3704
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003705bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01003706 if (!kIsVdexEnabled) {
3707 return true;
3708 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003709 // Write checksums
3710 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
3711 if (actual_offset != sizeof(VdexFile::Header)) {
3712 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3713 << " File: " << vdex_out->GetLocation();
3714 return false;
3715 }
3716
3717 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3718 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3719 if (!vdex_out->WriteFully(
3720 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3721 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3722 << vdex_out->GetLocation();
3723 return false;
3724 }
3725 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3726 }
3727
3728 // Write header.
3729 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003730 if (actual_offset != 0) {
3731 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3732 << " File: " << vdex_out->GetLocation();
3733 return false;
3734 }
3735
David Brazdil5d5a36b2016-09-14 15:34:10 +01003736 DCHECK_NE(vdex_dex_files_offset_, 0u);
3737 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
3738
3739 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003740 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3741 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003742
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003743 VdexFile::Header vdex_header(oat_dex_files_.size(),
3744 dex_section_size,
3745 verifier_deps_section_size,
3746 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003747 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
3748 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003749 return false;
3750 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003751 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003752
David Brazdil5d5a36b2016-09-14 15:34:10 +01003753 if (!vdex_out->Flush()) {
3754 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3755 << " File: " << vdex_out->GetLocation();
3756 return false;
3757 }
3758
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003759 return true;
3760}
3761
Vladimir Markof4da6752014-08-01 19:04:18 +01003762bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003763 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3764}
3765
3766bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003767 static const uint8_t kPadding[] = {
3768 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3769 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003770 DCHECK_LE(size, sizeof(kPadding));
3771 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003772 return false;
3773 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003774 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01003775 return true;
3776}
3777
Vladimir Marko944da602016-02-19 12:27:55 +00003778void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3779 DCHECK(dex_files_ != nullptr);
3780 DCHECK(relative_patcher_ != nullptr);
3781 DCHECK_NE(oat_data_offset_, 0u);
3782 if (image_writer_ != nullptr && !dex_files_->empty()) {
3783 // The oat data begin may not be initialized yet but the oat file offset is ready.
3784 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3785 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3786 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01003787 }
3788}
3789
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003790OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3791 DexFileSource source,
3792 CreateTypeLookupTable create_type_lookup_table)
3793 : source_(source),
3794 create_type_lookup_table_(create_type_lookup_table),
3795 dex_file_size_(0),
3796 offset_(0),
3797 dex_file_location_size_(strlen(dex_file_location)),
3798 dex_file_location_data_(dex_file_location),
3799 dex_file_location_checksum_(0u),
3800 dex_file_offset_(0u),
3801 class_offsets_offset_(0u),
3802 lookup_table_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003803 method_bss_mapping_offset_(0u),
Mathieu Chartier120aa282017-08-05 16:03:03 -07003804 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003805 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07003806}
3807
3808size_t OatWriter::OatDexFile::SizeOf() const {
3809 return sizeof(dex_file_location_size_)
3810 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003811 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08003812 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003813 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003814 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003815 + sizeof(method_bss_mapping_offset_)
3816 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003817}
3818
3819bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3820 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003821 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003822
Vladimir Markoe079e212016-05-25 12:49:49 +01003823 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003824 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003825 return false;
3826 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003827 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003828
Vladimir Markoe079e212016-05-25 12:49:49 +01003829 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003830 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003831 return false;
3832 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003833 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003834
Vladimir Markoe079e212016-05-25 12:49:49 +01003835 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003836 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003837 return false;
3838 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003839 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003840
Vladimir Markoe079e212016-05-25 12:49:49 +01003841 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003842 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003843 return false;
3844 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003845 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003846
Vladimir Markoe079e212016-05-25 12:49:49 +01003847 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003848 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3849 return false;
3850 }
3851 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3852
Vladimir Markoe079e212016-05-25 12:49:49 +01003853 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003854 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3855 return false;
3856 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003857 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003858
Mathieu Chartier120aa282017-08-05 16:03:03 -07003859 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
3860 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
3861 return false;
3862 }
3863 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
3864
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003865 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
3866 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
3867 return false;
3868 }
3869 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
3870
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003871 return true;
3872}
3873
3874bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003875 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003876 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
3877 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003878 return false;
3879 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003880 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003881 return true;
3882}
3883
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003884OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003885 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003886 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003887 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003888 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003889 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07003890
Brian Carlstromba150c32013-08-27 17:31:03 -07003891 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
3892
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003893 method_offsets_.resize(compiled_methods_with_code);
3894 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07003895
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003896 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
3897 // We only create this instance if there are at least some compiled.
3898 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003899 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07003900 method_bitmap_size_ = method_bitmap_->GetSizeOf();
3901 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
3902 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
3903 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003904 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07003905 method_bitmap_size_ = 0;
3906 }
3907
3908 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003909 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003910 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003911 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
3912 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003913 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003914 method_bitmap_->SetBit(i);
3915 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003916 } else {
3917 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07003918 }
3919 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003920}
3921
Brian Carlstrom265091e2013-01-30 14:08:26 -08003922size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003923 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07003924 + method_bitmap_size_
3925 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07003926}
3927
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003928bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
3929 OutputStream* out,
3930 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08003931 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01003932 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003933 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003934 return false;
3935 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003936 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003937
Vladimir Markoe079e212016-05-25 12:49:49 +01003938 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003939 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003940 return false;
3941 }
3942 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003943 return true;
3944}
Vladimir Marko49b0f452015-12-10 13:49:19 +00003945
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003946bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003947 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003948 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003949 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003950 return false;
3951 }
3952 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003953
Vladimir Markoe079e212016-05-25 12:49:49 +01003954 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003955 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003956 return false;
3957 }
3958 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
3959 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003960
Vladimir Markoe079e212016-05-25 12:49:49 +01003961 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08003962 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003963 return false;
3964 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003965 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003966 return true;
3967}
3968
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01003969const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
3970 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01003971 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01003972 uint32_t utf16_length;
3973 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
3974 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
3975 InternTable::Utf8String string(utf16_length,
3976 utf8_data,
3977 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
3978 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
3979 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
3980 auto it = table.Find(string);
3981 if (it != table.end()) {
3982 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
3983 }
3984 }
3985 LOG(FATAL) << "Did not find boot image string " << utf8_data;
3986 UNREACHABLE();
3987}
3988
Vladimir Marko94ec2db2017-09-06 17:21:03 +01003989const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
3990 dex::TypeIndex type_idx)
3991 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
3992 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
3993 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
3994 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
3995 for (const ClassTable::ClassSet& class_set : table->classes_) {
3996 auto it = class_set.Find(pair);
3997 if (it != class_set.end()) {
3998 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
3999 }
4000 }
4001 LOG(FATAL) << "Did not find boot image class " << descriptor;
4002 UNREACHABLE();
4003}
4004
Vladimir Marko74527972016-11-29 15:57:32 +00004005} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004006} // namespace art