blob: 909ba22f2127a5433ea32ac2554ae5dd07f46805 [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
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000298 // Dex file size. Initialized when copying the dex file in the
299 // WriteDexFile methods.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000300 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000301
302 // Offset of start of OatDexFile from beginning of OatHeader. It is
303 // used to validate file position when writing.
304 size_t offset_;
305
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000306 ///// Start of data to write to vdex/oat file.
307
308 const uint32_t dex_file_location_size_;
309 const char* const dex_file_location_data_;
310
311 // The checksum of the dex file. Initialized when adding a DexFile
312 // source.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000313 uint32_t dex_file_location_checksum_;
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000314
315 // Offset of the dex file in the vdex file. Set when writing dex files in
316 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000317 uint32_t dex_file_offset_;
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000318
319 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000320 uint32_t lookup_table_offset_;
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000321
322 // Offset of dex sections that will have different runtime madvise states.
323 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700324 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000325
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000326 // Class and BSS offsets set in PrepareLayout.
327 uint32_t class_offsets_offset_;
328 uint32_t method_bss_mapping_offset_;
329
330 // Data to write to a separate section. We set the length
331 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000332 dchecked_vector<uint32_t> class_offsets_;
333
Mathieu Chartier120aa282017-08-05 16:03:03 -0700334 // Dex section layout info to serialize.
335 DexLayoutSections dex_sections_layout_;
336
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000337 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000338 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000339 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
340};
341
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100342#define DCHECK_OFFSET() \
343 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
344 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
345
346#define DCHECK_OFFSET_() \
347 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
348 << "file_offset=" << file_offset << " offset_=" << offset_
349
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700350OatWriter::OatWriter(bool compiling_boot_image,
351 TimingLogger* timings,
352 ProfileCompilationInfo* info,
353 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000354 : write_state_(WriteState::kAddingDexFileSources),
355 timings_(timings),
356 raw_dex_files_(),
357 zip_archives_(),
358 zipped_dex_files_(),
359 zipped_dex_file_locations_(),
360 compiler_driver_(nullptr),
361 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800362 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000363 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100364 vdex_size_(0u),
365 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100366 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100367 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100368 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000369 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000370 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100371 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000372 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100373 bss_method_entry_references_(),
374 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000375 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000376 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100377 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100378 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700379 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100380 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000381 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700382 size_dex_file_alignment_(0),
383 size_executable_offset_alignment_(0),
384 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700385 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700386 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100387 size_verifier_deps_(0),
388 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100389 size_quickening_info_(0),
390 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700391 size_interpreter_to_interpreter_bridge_(0),
392 size_interpreter_to_compiled_code_bridge_(0),
393 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800394 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700395 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700396 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700397 size_quick_to_interpreter_bridge_(0),
398 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100399 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700400 size_code_(0),
401 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100402 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100403 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700404 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700405 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700406 size_oat_dex_file_location_size_(0),
407 size_oat_dex_file_location_data_(0),
408 size_oat_dex_file_location_checksum_(0),
409 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000410 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000411 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700412 size_oat_dex_file_dex_layout_sections_offset_(0),
413 size_oat_dex_file_dex_layout_sections_(0),
414 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100415 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000416 size_oat_lookup_table_alignment_(0),
417 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000418 size_oat_class_offsets_alignment_(0),
419 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700420 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700421 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700422 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100423 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100424 size_method_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000425 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700426 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700427 profile_compilation_info_(info),
428 compact_dex_level_(compact_dex_level) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000429}
430
431bool OatWriter::AddDexFileSource(const char* filename,
432 const char* location,
433 CreateTypeLookupTable create_type_lookup_table) {
434 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
435 uint32_t magic;
436 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700437 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
438 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000439 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
440 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700441 } else if (DexFileLoader::IsMagicValid(magic)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000442 // The file is open for reading, not writing, so it's OK to let the File destructor
443 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700444 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000445 oat_dex_files_.emplace_back(location,
446 DexFileSource(raw_dex_files_.back().get()),
447 create_type_lookup_table);
448 } else if (IsZipMagic(magic)) {
449 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
450 return false;
451 }
452 } else {
453 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
454 return false;
455 }
456 return true;
457}
458
459// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700460bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000461 const char* location,
462 CreateTypeLookupTable create_type_lookup_table) {
463 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
464 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700465 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000466 ZipArchive* zip_archive = zip_archives_.back().get();
467 if (zip_archive == nullptr) {
468 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
469 << error_msg;
470 return false;
471 }
472 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700473 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000474 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
475 if (entry == nullptr) {
476 break;
477 }
478 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700479 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480 const char* full_location = zipped_dex_file_locations_.back().c_str();
481 oat_dex_files_.emplace_back(full_location,
482 DexFileSource(zipped_dex_files_.back().get()),
483 create_type_lookup_table);
Nicolas Geoffray97a042e2017-11-16 10:49:59 +0000484 // Override the checksum from header with the CRC from ZIP entry.
485 oat_dex_files_.back().dex_file_location_checksum_ = zipped_dex_files_.back()->GetCrc32();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000486 }
487 if (zipped_dex_file_locations_.empty()) {
488 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
489 return false;
490 }
491 return true;
492}
493
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000494// Add dex file source(s) from a vdex file specified by a file handle.
495bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
496 const char* location,
497 CreateTypeLookupTable create_type_lookup_table) {
498 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
499 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000500 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000501 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
502 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000503 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
504 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000505 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700506
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700507 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000508 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
509 return false;
510 }
511 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700512 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000513 const char* full_location = zipped_dex_file_locations_.back().c_str();
514 oat_dex_files_.emplace_back(full_location,
515 DexFileSource(current_dex_data),
516 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000517 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000518 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000519
520 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
521 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
522 return false;
523 }
524
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000525 if (oat_dex_files_.empty()) {
526 LOG(ERROR) << "No dex files in vdex file created from " << location;
527 return false;
528 }
529 return true;
530}
531
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000532// Add dex file source from raw memory.
533bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
534 const char* location,
535 uint32_t location_checksum,
536 CreateTypeLookupTable create_type_lookup_table) {
537 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
538 if (data.size() < sizeof(DexFile::Header)) {
539 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
540 << data.size() << " File: " << location;
541 return false;
542 }
543 if (!ValidateDexFileHeader(data.data(), location)) {
544 return false;
545 }
546 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
547 if (data.size() < header->file_size_) {
548 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
549 << " file size from header: " << header->file_size_ << " File: " << location;
550 return false;
551 }
552
553 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
554 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
555 return true;
556}
557
Calin Juravle1ce70852017-06-28 10:59:03 -0700558dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
559 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000560 locations.reserve(oat_dex_files_.size());
561 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
562 locations.push_back(oat_dex_file.GetLocation());
563 }
564 return locations;
565}
566
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700567bool OatWriter::MayHaveCompiledMethods() const {
568 return CompilerFilter::IsAnyCompilationEnabled(
569 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
570}
571
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000572bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100573 File* vdex_file,
574 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000575 InstructionSet instruction_set,
576 const InstructionSetFeatures* instruction_set_features,
577 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800578 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000579 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000580 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
581 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
582 CHECK(write_state_ == WriteState::kAddingDexFileSources);
583
David Brazdil7b49e6c2016-09-01 11:06:18 +0100584 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
585 if (!RecordOatDataOffset(oat_rodata)) {
586 return false;
587 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000588
589 std::unique_ptr<MemMap> dex_files_map;
590 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100591
592 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000593
594 // Reserve space for Vdex header and checksums.
595 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100596 oat_size_ = InitOatHeader(instruction_set,
597 instruction_set_features,
598 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
599 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100600
601 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
602
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000603 std::unique_ptr<BufferedOutputStream> vdex_out =
604 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
605 // Write DEX files into VDEX, mmap and open them.
606 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
607 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
608 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000609 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000610
Mathieu Chartier120aa282017-08-05 16:03:03 -0700611 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000612 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
613 return false;
614 }
615
Mathieu Chartier120aa282017-08-05 16:03:03 -0700616 // Write dex layout sections into the oat file.
617 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
618 return false;
619 }
620
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000621 *opened_dex_files_map = std::move(dex_files_map);
622 *opened_dex_files = std::move(dex_files);
623 write_state_ = WriteState::kPrepareLayout;
624 return true;
625}
626
Vladimir Marko74527972016-11-29 15:57:32 +0000627void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000628 CHECK(write_state_ == WriteState::kPrepareLayout);
629
Vladimir Marko944da602016-02-19 12:27:55 +0000630 relative_patcher_ = relative_patcher;
631 SetMultiOatRelativePatcherAdjustment();
632
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000633 if (compiling_boot_image_) {
634 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800635 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100636 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000637 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100638
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100639 {
640 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
641 InitBssLayout(instruction_set);
642 }
643
David Brazdil7b49e6c2016-09-01 11:06:18 +0100644 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800645 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100646 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
647 offset = InitClassOffsets(offset);
648 }
649 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000650 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800651 offset = InitOatClasses(offset);
652 }
653 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100654 TimingLogger::ScopedTiming split("InitMethodBssMappings", timings_);
655 offset = InitMethodBssMappings(offset);
656 }
657 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000658 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100659 offset = InitOatMaps(offset);
660 }
661 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100662 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
663 oat_header_->SetOatDexFilesOffset(offset);
664 offset = InitOatDexFiles(offset);
665 }
666 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000667 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800668 offset = InitOatCode(offset);
669 }
670 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000671 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800672 offset = InitOatCodeDexFiles(offset);
673 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100674 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100675 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100676
Brian Carlstrome24fa612011-09-29 00:53:55 -0700677 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800678 if (compiling_boot_image_) {
679 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000680 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800681 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000682
683 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700684}
685
Ian Rogers0571d352011-11-03 19:51:38 -0700686OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700687}
688
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100689class OatWriter::DexMethodVisitor {
690 public:
691 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100692 : writer_(writer),
693 offset_(offset),
694 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700695 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100696
697 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
698 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700699 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100700 dex_file_ = dex_file;
701 class_def_index_ = class_def_index;
702 return true;
703 }
704
705 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
706
707 virtual bool EndClass() {
708 if (kIsDebugBuild) {
709 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700710 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100711 }
712 return true;
713 }
714
715 size_t GetOffset() const {
716 return offset_;
717 }
718
719 protected:
720 virtual ~DexMethodVisitor() { }
721
722 OatWriter* const writer_;
723
724 // The offset is usually advanced for each visited method by the derived class.
725 size_t offset_;
726
727 // The dex file and class def index are set in StartClass().
728 const DexFile* dex_file_;
729 size_t class_def_index_;
730};
731
732class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
733 public:
734 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100735 : DexMethodVisitor(writer, offset),
736 oat_class_index_(0u),
737 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100738
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100739 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100740 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700741 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
742 // There are no oat classes if there aren't any compiled methods.
743 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
744 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100745 method_offsets_index_ = 0u;
746 return true;
747 }
748
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100749 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100750 ++oat_class_index_;
751 return DexMethodVisitor::EndClass();
752 }
753
754 protected:
755 size_t oat_class_index_;
756 size_t method_offsets_index_;
757};
758
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100759static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000760 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100761}
762
763static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000764 // The dextodexcompiler puts the quickening info table into the CompiledMethod
765 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100766 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
767}
768
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100769class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
770 public:
771 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
772 : DexMethodVisitor(writer, /* offset */ 0u) {}
773
774 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
775 const ClassDataItemIterator& it) OVERRIDE {
776 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
777 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
778 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100779 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100780 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
781 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
782 MethodReference target_method = patch.TargetMethod();
783 auto refs_it = writer_->bss_method_entry_references_.find(target_method.dex_file);
784 if (refs_it == writer_->bss_method_entry_references_.end()) {
785 refs_it = writer_->bss_method_entry_references_.Put(
786 target_method.dex_file,
787 BitVector(target_method.dex_file->NumMethodIds(),
788 /* expandable */ false,
789 Allocator::GetMallocAllocator()));
790 refs_it->second.ClearAllBits();
791 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700792 refs_it->second.SetBit(target_method.index);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100793 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
794 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
795 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
796 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
797 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
798 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
799 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100800 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
801 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100802 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100803 }
804 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100805 } else {
806 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100807 }
808 return true;
809 }
810};
811
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100812class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
813 public:
814 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100815 : DexMethodVisitor(writer, offset),
816 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100817 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000818 size_t num_classes = 0u;
819 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
820 num_classes += oat_dex_file.class_offsets_.size();
821 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700822 // If we aren't compiling only reserve headers.
823 writer_->oat_class_headers_.reserve(num_classes);
824 if (writer->MayHaveCompiledMethods()) {
825 writer->oat_classes_.reserve(num_classes);
826 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100827 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100828 // If there are any classes, the class offsets allocation aligns the offset.
829 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100830 }
831
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100832 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833 DexMethodVisitor::StartClass(dex_file, class_def_index);
834 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100835 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100836 return true;
837 }
838
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300839 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100840 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841 // Fill in the compiled_methods_ array for methods that have a
842 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100843 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100844 // OatMethodOffsets for the compiled methods.
845 uint32_t method_idx = it.GetMemberIndex();
846 CompiledMethod* compiled_method =
847 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
848 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100849 if (HasCompiledCode(compiled_method)) {
850 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100851 }
852 return true;
853 }
854
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100855 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100856 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100857 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700858 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
859 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700860 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
861 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700862 // The oat class status is used only for verification of resolved classes,
863 // so use kStatusErrorResolved whether the class was resolved or unresolved
864 // during compile-time verification.
865 status = mirror::Class::kStatusErrorResolved;
866 } else {
867 status = mirror::Class::kStatusNotReady;
868 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100869 }
870
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700871 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100872 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700873 compiled_methods_.size(),
874 status);
875 OatClassHeader& header = writer_->oat_class_headers_.back();
876 offset_ += header.SizeOf();
877 if (writer_->MayHaveCompiledMethods()) {
878 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100879 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700880 header.type_);
881 offset_ += writer_->oat_classes_.back().SizeOf();
882 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100883 return DexMethodVisitor::EndClass();
884 }
885
886 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000887 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100888 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100889};
890
Igor Murashkin545412b2017-08-17 15:26:54 -0700891// CompiledMethod + metadata required to do ordered method layout.
892//
893// See also OrderedMethodVisitor.
894struct OatWriter::OrderedMethodData {
895 ProfileCompilationInfo::MethodHotness method_hotness;
896 OatClass* oat_class;
897 CompiledMethod* compiled_method;
898 MethodReference method_reference;
899 size_t method_offsets_index;
900
901 size_t class_def_index;
902 uint32_t access_flags;
903 const DexFile::CodeItem* code_item;
904
905 // A value of -1 denotes missing debug info
906 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
907 // Index into writer_->method_info_
908 size_t debug_info_idx;
909
910 bool HasDebugInfo() const {
911 return debug_info_idx != kDebugInfoIdxInvalid;
912 }
913
914 // Bin each method according to the profile flags.
915 //
916 // Groups by e.g.
917 // -- not hot at all
918 // -- hot
919 // -- hot and startup
920 // -- hot and post-startup
921 // -- hot and startup and poststartup
922 // -- startup
923 // -- startup and post-startup
924 // -- post-startup
925 //
926 // (See MethodHotness enum definition for up-to-date binning order.)
927 bool operator<(const OrderedMethodData& other) const {
928 if (kOatWriterForceOatCodeLayout) {
929 // Development flag: Override default behavior by sorting by name.
930
931 std::string name = method_reference.PrettyMethod();
932 std::string other_name = other.method_reference.PrettyMethod();
933 return name < other_name;
934 }
935
936 // Use the profile's method hotness to determine sort order.
937 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
938 return true;
939 }
940
941 // Default: retain the original order.
942 return false;
943 }
944
945 private:
946 // Used to determine relative order for OAT code layout when determining
947 // binning.
948 size_t GetMethodHotnessOrder() const {
949 bool hotness[] = {
950 method_hotness.IsHot(),
951 method_hotness.IsStartup(),
952 method_hotness.IsPostStartup()
953 };
954
955
956 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
957 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
958 // time that memory is referenced in the process.
959
960 size_t hotness_bits = 0;
961 for (size_t i = 0; i < arraysize(hotness); ++i) {
962 if (hotness[i]) {
963 hotness_bits |= (1 << i);
964 }
965 }
966
967 if (kIsDebugBuild) {
968 // Check for bins that are always-empty given a real profile.
969 if (method_hotness.IsHot() &&
970 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
971 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -0700972 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
973 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -0700974 // This is not fatal, so only warn.
975 }
976 }
977
978 return hotness_bits;
979 }
980};
981
982// Given a queue of CompiledMethod in some total order,
983// visit each one in that order.
984class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100985 public:
Igor Murashkin545412b2017-08-17 15:26:54 -0700986 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
987 : ordered_methods_(std::move(ordered_methods)) {
988 }
989
990 virtual ~OrderedMethodVisitor() {}
991
992 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
993 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
994 if (!VisitStart()) {
995 return false;
996 }
997
998 for (const OrderedMethodData& method_data : ordered_methods_) {
999 if (!VisitMethod(method_data)) {
1000 return false;
1001 }
1002 }
1003
1004 return VisitComplete();
1005 }
1006
1007 // Invoked once at the beginning, prior to visiting anything else.
1008 //
1009 // Return false to abort further visiting.
1010 virtual bool VisitStart() { return true; }
1011
1012 // Invoked repeatedly in the order specified by `ordered_methods`.
1013 //
1014 // Return false to short-circuit and to stop visiting further methods.
1015 virtual bool VisitMethod(const OrderedMethodData& method_data)
1016 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1017
1018 // Invoked once at the end, after every other method has been successfully visited.
1019 //
1020 // Return false to indicate the overall `Visit` has failed.
1021 virtual bool VisitComplete() = 0;
1022
1023 OrderedMethodList ReleaseOrderedMethods() {
1024 return std::move(ordered_methods_);
1025 }
1026
1027 private:
1028 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1029 // Methods can be inserted more than once in case of duplicated methods.
1030 OrderedMethodList ordered_methods_;
1031};
1032
1033// Visit every compiled method in order to determine its order within the OAT file.
1034// Methods from the same class do not need to be adjacent in the OAT code.
1035class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1036 public:
1037 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1038 : OatDexMethodVisitor(writer, offset) {
1039 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001040
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001041 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001042 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001043 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001044 }
1045
Igor Murashkin545412b2017-08-17 15:26:54 -07001046 bool VisitMethod(size_t class_def_method_index,
1047 const ClassDataItemIterator& it)
1048 OVERRIDE
1049 REQUIRES_SHARED(Locks::mutator_lock_) {
1050 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1051
Vladimir Marko49b0f452015-12-10 13:49:19 +00001052 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001053 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1054
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001055 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001056 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001057
Igor Murashkin545412b2017-08-17 15:26:54 -07001058 {
1059 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1060 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1061 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001062
Igor Murashkin545412b2017-08-17 15:26:54 -07001063 // Debug method info must be pushed in the original order
1064 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1065 // ElfCompilationUnitWriter::Write requires this.
1066 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1067 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1068 writer_->method_info_.push_back(info);
1069
1070 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1071 // once we know the offsets.
1072 //
1073 // Store the index into writer_->method_info_ since future push-backs
1074 // could reallocate and change the underlying data address.
1075 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001076 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001077 }
1078
1079 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1080
1081 // Lookup method hotness from profile, if available.
1082 // Otherwise assume a default of none-hotness.
1083 ProfileCompilationInfo::MethodHotness method_hotness =
1084 writer_->profile_compilation_info_ != nullptr
1085 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1086 : ProfileCompilationInfo::MethodHotness();
1087
1088 // Handle duplicate methods by pushing them repeatedly.
1089 OrderedMethodData method_data = {
1090 method_hotness,
1091 oat_class,
1092 compiled_method,
1093 method_ref,
1094 method_offsets_index_,
1095 class_def_index_,
1096 it.GetMethodAccessFlags(),
1097 it.GetMethodCodeItem(),
1098 debug_info_idx
1099 };
1100 ordered_methods_.push_back(method_data);
1101
1102 method_offsets_index_++;
1103 }
1104
1105 return true;
1106 }
1107
1108 OrderedMethodList ReleaseOrderedMethods() {
1109 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1110 // Sort by the method ordering criteria (in OrderedMethodData).
1111 // Since most methods will have the same ordering criteria,
1112 // we preserve the original insertion order within the same sort order.
1113 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1114 } else {
1115 // The profile-less behavior is as if every method had 0 hotness
1116 // associated with it.
1117 //
1118 // Since sorting all methods with hotness=0 should give back the same
1119 // order as before, don't do anything.
1120 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1121 }
1122
1123 return std::move(ordered_methods_);
1124 }
1125
1126 private:
1127 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1128 // Methods can be inserted more than once in case of duplicated methods.
1129 OrderedMethodList ordered_methods_;
1130};
1131
1132// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1133class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1134 public:
1135 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1136 size_t offset,
1137 OrderedMethodList ordered_methods)
1138 : LayoutReserveOffsetCodeMethodVisitor(writer,
1139 offset,
1140 writer->GetCompilerDriver()->GetCompilerOptions(),
1141 std::move(ordered_methods)) {
1142 }
1143
1144 virtual bool VisitComplete() OVERRIDE {
1145 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1146 if (generate_debug_info_) {
1147 std::vector<debug::MethodDebugInfo> thunk_infos =
1148 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1149 writer_->method_info_.insert(writer_->method_info_.end(),
1150 std::make_move_iterator(thunk_infos.begin()),
1151 std::make_move_iterator(thunk_infos.end()));
1152 }
1153 return true;
1154 }
1155
1156 virtual bool VisitMethod(const OrderedMethodData& method_data)
1157 OVERRIDE
1158 REQUIRES_SHARED(Locks::mutator_lock_) {
1159 OatClass* oat_class = method_data.oat_class;
1160 CompiledMethod* compiled_method = method_data.compiled_method;
1161 const MethodReference& method_ref = method_data.method_reference;
1162 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1163 size_t class_def_index = method_data.class_def_index;
1164 uint32_t access_flags = method_data.access_flags;
1165 const DexFile::CodeItem* code_item = method_data.code_item;
1166 bool has_debug_info = method_data.HasDebugInfo();
1167 size_t debug_info_idx = method_data.debug_info_idx;
1168
1169 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1170
1171 // Derived from CompiledMethod.
1172 uint32_t quick_code_offset = 0;
1173
1174 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1175 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1176 uint32_t thumb_offset = compiled_method->CodeDelta();
1177
1178 // Deduplicate code arrays if we are not producing debuggable code.
1179 bool deduped = true;
1180 if (debuggable_) {
1181 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1182 if (quick_code_offset != 0u) {
1183 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1184 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001185 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001186 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1187 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001188 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001189 } else {
1190 quick_code_offset = dedupe_map_.GetOrCreate(
1191 compiled_method,
1192 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1193 deduped = false;
1194 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1195 });
1196 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001197
Igor Murashkin545412b2017-08-17 15:26:54 -07001198 if (code_size != 0) {
1199 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1200 // TODO: Should this be a hard failure?
1201 LOG(WARNING) << "Multiple definitions of "
1202 << method_ref.dex_file->PrettyMethod(method_ref.index)
1203 << " offsets " << relative_patcher_->GetOffset(method_ref)
1204 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001205 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001206 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1207 }
1208 }
1209
1210 // Update quick method header.
1211 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1212 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1213 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1214 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1215 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1216 // to 0-offset and we need to adjust it by code_offset.
1217 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001218 CHECK(!compiled_method->GetQuickCode().empty());
1219 // If the code is compiled, we write the offset of the stack map relative
1220 // to the code.
1221 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001222 vmap_table_offset += code_offset;
1223 DCHECK_LT(vmap_table_offset, code_offset);
1224 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001225 if (method_info_offset != 0u) {
1226 method_info_offset += code_offset;
1227 DCHECK_LT(method_info_offset, code_offset);
1228 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001229 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1230 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1231 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1232 *method_header = OatQuickMethodHeader(vmap_table_offset,
1233 method_info_offset,
1234 frame_size_in_bytes,
1235 core_spill_mask,
1236 fp_spill_mask,
1237 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001238
Igor Murashkin545412b2017-08-17 15:26:54 -07001239 if (!deduped) {
1240 // Update offsets. (Checksum is updated when writing.)
1241 offset_ += sizeof(*method_header); // Method header is prepended before code.
1242 offset_ += code_size;
1243 // Record absolute patch locations.
1244 if (!compiled_method->GetPatches().empty()) {
1245 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1246 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1247 if (!patch.IsPcRelative()) {
1248 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001249 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001250 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001251 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001252 }
1253
Igor Murashkin545412b2017-08-17 15:26:54 -07001254 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1255 if (generate_debug_info_ && code_size != 0) {
1256 DCHECK(has_debug_info);
1257
1258 bool has_code_info = method_header->IsOptimized();
1259 // Record debug information for this function if we are doing that.
1260 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1261 DCHECK(info.trampoline_name.empty());
1262 info.dex_file = method_ref.dex_file;
1263 info.class_def_index = class_def_index;
1264 info.dex_method_index = method_ref.index;
1265 info.access_flags = access_flags;
1266 info.code_item = code_item;
1267 info.isa = compiled_method->GetInstructionSet();
1268 info.deduped = deduped;
1269 info.is_native_debuggable = native_debuggable_;
1270 info.is_optimized = method_header->IsOptimized();
1271 info.is_code_address_text_relative = true;
1272 info.code_address = code_offset - executable_offset_;
1273 info.code_size = code_size;
1274 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1275 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1276 info.cfi = compiled_method->GetCFIInfo();
1277 } else {
1278 DCHECK(!has_debug_info);
1279 }
1280
1281 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1282 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1283 offsets->code_offset_ = quick_code_offset;
1284
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001285 return true;
1286 }
1287
Igor Murashkin545412b2017-08-17 15:26:54 -07001288 size_t GetOffset() const {
1289 return offset_;
1290 }
1291
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001292 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001293 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1294 size_t offset,
1295 const CompilerOptions& compiler_options,
1296 OrderedMethodList ordered_methods)
1297 : OrderedMethodVisitor(std::move(ordered_methods)),
1298 writer_(writer),
1299 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001300 relative_patcher_(writer->relative_patcher_),
1301 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1302 debuggable_(compiler_options.GetDebuggable()),
1303 native_debuggable_(compiler_options.GetNativeDebuggable()),
1304 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1305 writer->absolute_patch_locations_.reserve(
1306 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1307 }
1308
Vladimir Marko20f85592015-03-19 10:07:02 +00001309 struct CodeOffsetsKeyComparator {
1310 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001311 // Code is deduplicated by CompilerDriver, compare only data pointers.
1312 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1313 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001314 }
1315 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001316 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1317 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001318 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001319 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1320 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1321 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001322 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1323 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001324 }
1325 return false;
1326 }
1327 };
1328
David Srbecky009e2a62015-04-15 02:46:30 +01001329 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001330 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001331 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001332 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001333 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1334 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001335 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1336 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1337 }
1338
Igor Murashkin545412b2017-08-17 15:26:54 -07001339 OatWriter* writer_;
1340
1341 // Offset of the code of the compiled methods.
1342 size_t offset_;
1343
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001344 // Deduplication is already done on a pointer basis by the compiler driver,
1345 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001346 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001347
Vladimir Marko1b404a82017-09-01 13:35:26 +01001348 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001349 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001350 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001351 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001352 const bool native_debuggable_;
1353 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001354};
1355
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001356class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1357 public:
1358 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001359 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001360
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001361 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001362 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001363 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001364 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1365
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001366 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001367 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001368 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001369
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001370 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1371 uint32_t map_size = map.size() * sizeof(map[0]);
1372 if (map_size != 0u) {
1373 size_t offset = dedupe_map_.GetOrCreate(
1374 map.data(),
1375 [this, map_size]() {
1376 uint32_t new_offset = offset_;
1377 offset_ += map_size;
1378 return new_offset;
1379 });
1380 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1381 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1382 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001383 }
1384 ++method_offsets_index_;
1385 }
1386
1387 return true;
1388 }
1389
1390 private:
1391 // Deduplication is already done on a pointer basis by the compiler driver,
1392 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001393 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001394};
1395
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001396class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1397 public:
1398 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1399
1400 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001401 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001402 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1403 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1404
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001405 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001406 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1407 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1408 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1409 const uint32_t map_size = map.size() * sizeof(map[0]);
1410 if (map_size != 0u) {
1411 size_t offset = dedupe_map_.GetOrCreate(
1412 map.data(),
1413 [this, map_size]() {
1414 uint32_t new_offset = offset_;
1415 offset_ += map_size;
1416 return new_offset;
1417 });
1418 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1419 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1420 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1421 }
1422 ++method_offsets_index_;
1423 }
1424
1425 return true;
1426 }
1427
1428 private:
1429 // Deduplication is already done on a pointer basis by the compiler driver,
1430 // so we can simply compare the pointers to find out if things are duplicated.
1431 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1432};
1433
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1435 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001436 InitImageMethodVisitor(OatWriter* writer,
1437 size_t offset,
1438 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001439 : OatDexMethodVisitor(writer, offset),
1440 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001441 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001442 dex_files_(dex_files),
1443 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001444
1445 // Handle copied methods here. Copy pointer to quick code from
1446 // an origin method to a copied method only if they are
1447 // in the same oat file. If the origin and the copied methods are
1448 // in different oat files don't touch the copied method.
1449 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001450 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001451 REQUIRES_SHARED(Locks::mutator_lock_) {
1452 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1453 // Skip classes that are not in the image.
1454 if (!IsImageClass()) {
1455 return true;
1456 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001457 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001458 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1459 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1460 if (klass != nullptr) {
1461 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1462 // Find origin method. Declaring class and dex_method_idx
1463 // in the copied method should be the same as in the origin
1464 // method.
1465 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001466 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001467 declaring_class->GetDexCache(),
1468 method.GetDexMethodIndex(),
1469 pointer_size_);
1470 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001471 CHECK(!origin->IsDirect());
1472 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001473 if (IsInOatFile(&declaring_class->GetDexFile())) {
1474 const void* code_ptr =
1475 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1476 if (code_ptr == nullptr) {
1477 methods_to_process_.push_back(std::make_pair(&method, origin));
1478 } else {
1479 method.SetEntryPointFromQuickCompiledCodePtrSize(
1480 code_ptr, pointer_size_);
1481 }
1482 }
1483 }
1484 }
1485 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001486 }
1487
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001488 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001489 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001490 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001491 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001492 return true;
1493 }
1494
Vladimir Marko49b0f452015-12-10 13:49:19 +00001495 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001496 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1497
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001498 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001499 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001500 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1501 offsets = oat_class->method_offsets_[method_offsets_index_];
1502 ++method_offsets_index_;
1503 }
1504
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001505 Thread* self = Thread::Current();
1506 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001507 ArtMethod* method;
1508 if (writer_->HasBootImage()) {
1509 const InvokeType invoke_type = it.GetMethodInvokeType(
1510 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001511 // Unchecked as we hold mutator_lock_ on entry.
1512 ScopedObjectAccessUnchecked soa(self);
1513 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001514 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001515 *dex_file_,
1516 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001517 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001518 ScopedNullHandle<mirror::ClassLoader>(),
1519 nullptr,
1520 invoke_type);
1521 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001522 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001523 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001524 self->AssertPendingException();
1525 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001526 std::string dump = exc->Dump();
1527 LOG(FATAL) << dump;
1528 UNREACHABLE();
1529 }
1530 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001531 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001532 // 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 +01001533 // entrypoint. This is not fatal since we shall use a resolution method.
1534 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001535 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001536 if (method != nullptr &&
1537 compiled_method != nullptr &&
1538 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001539 method->SetEntryPointFromQuickCompiledCodePtrSize(
1540 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1541 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001542
1543 return true;
1544 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001545
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001546 // Check whether current class is image class
1547 bool IsImageClass() {
1548 const DexFile::TypeId& type_id =
1549 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1550 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1551 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1552 }
1553
1554 // Check whether specified dex file is in the compiled oat file.
1555 bool IsInOatFile(const DexFile* dex_file) {
1556 return ContainsElement(*dex_files_, dex_file);
1557 }
1558
1559 // Assign a pointer to quick code for copied methods
1560 // not handled in the method StartClass
1561 void Postprocess() {
1562 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1563 ArtMethod* method = p.first;
1564 ArtMethod* origin = p.second;
1565 const void* code_ptr =
1566 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1567 if (code_ptr != nullptr) {
1568 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1569 }
1570 }
1571 }
1572
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001573 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001574 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001575 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001576 const std::vector<const DexFile*>* dex_files_;
1577 ClassLinker* const class_linker_;
1578 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001579};
1580
Igor Murashkin545412b2017-08-17 15:26:54 -07001581class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001582 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001583 WriteCodeMethodVisitor(OatWriter* writer,
1584 OutputStream* out,
1585 const size_t file_offset,
1586 size_t relative_offset,
1587 OrderedMethodList ordered_methods)
1588 : OrderedMethodVisitor(std::move(ordered_methods)),
1589 writer_(writer),
1590 offset_(relative_offset),
1591 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001592 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1593 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1594 out_(out),
1595 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001596 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001597 dex_cache_(nullptr),
1598 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001599 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001600 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001601 // If we're creating the image, the address space must be ready so that we can apply patches.
1602 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001603 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001604 }
1605
Igor Murashkin545412b2017-08-17 15:26:54 -07001606 virtual bool VisitStart() OVERRIDE {
1607 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001608 }
1609
Igor Murashkin545412b2017-08-17 15:26:54 -07001610 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001611 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001612 dex_file_ = dex_file;
1613
1614 // Ordered method visiting is only for compiled methods.
1615 DCHECK(writer_->MayHaveCompiledMethods());
1616
Mathieu Chartier72041a02017-07-14 18:23:25 -07001617 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1618 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1619 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1620 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1621 DCHECK(dex_cache_ != nullptr);
1622 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001623 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001624 }
1625
1626 virtual bool VisitComplete() {
1627 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1628 if (UNLIKELY(offset_ == 0u)) {
1629 PLOG(ERROR) << "Failed to write final relative call thunks";
1630 return false;
1631 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001632 return true;
1633 }
1634
Igor Murashkin545412b2017-08-17 15:26:54 -07001635 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001636 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001637 const MethodReference& method_ref = method_data.method_reference;
1638 UpdateDexFileAndDexCache(method_ref.dex_file);
1639
1640 OatClass* oat_class = method_data.oat_class;
1641 CompiledMethod* compiled_method = method_data.compiled_method;
1642 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001643
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001644 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001645 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001646 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001647
Igor Murashkin545412b2017-08-17 15:26:54 -07001648 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1649 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1650 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001651
Igor Murashkin545412b2017-08-17 15:26:54 -07001652 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1653 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1654
1655 // Deduplicate code arrays.
1656 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1657 if (method_offsets.code_offset_ > offset_) {
1658 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1659 if (offset_ == 0u) {
1660 ReportWriteFailure("relative call thunk", method_ref);
1661 return false;
1662 }
1663 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1664 if (alignment_size != 0) {
1665 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1666 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001667 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001668 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001669 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001670 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001671 }
1672 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1673 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1674 DCHECK_EQ(method_offsets.code_offset_,
1675 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1676 << dex_file_->PrettyMethod(method_ref.index);
1677 const OatQuickMethodHeader& method_header =
1678 oat_class->method_headers_[method_offsets_index];
1679 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1680 ReportWriteFailure("method header", method_ref);
1681 return false;
1682 }
1683 writer_->size_method_header_ += sizeof(method_header);
1684 offset_ += sizeof(method_header);
1685 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001686
Igor Murashkin545412b2017-08-17 15:26:54 -07001687 if (!compiled_method->GetPatches().empty()) {
1688 patched_code_.assign(quick_code.begin(), quick_code.end());
1689 quick_code = ArrayRef<const uint8_t>(patched_code_);
1690 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1691 uint32_t literal_offset = patch.LiteralOffset();
1692 switch (patch.GetType()) {
1693 case LinkerPatch::Type::kMethodBssEntry: {
1694 uint32_t target_offset =
1695 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1696 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1697 patch,
1698 offset_ + literal_offset,
1699 target_offset);
1700 break;
1701 }
1702 case LinkerPatch::Type::kCallRelative: {
1703 // NOTE: Relative calls across oat files are not supported.
1704 uint32_t target_offset = GetTargetOffset(patch);
1705 writer_->relative_patcher_->PatchCall(&patched_code_,
1706 literal_offset,
1707 offset_ + literal_offset,
1708 target_offset);
1709 break;
1710 }
1711 case LinkerPatch::Type::kStringRelative: {
1712 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1713 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1714 patch,
1715 offset_ + literal_offset,
1716 target_offset);
1717 break;
1718 }
1719 case LinkerPatch::Type::kStringInternTable: {
1720 uint32_t target_offset = GetInternTableEntryOffset(patch);
1721 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1722 patch,
1723 offset_ + literal_offset,
1724 target_offset);
1725 break;
1726 }
1727 case LinkerPatch::Type::kStringBssEntry: {
1728 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1729 uint32_t target_offset =
1730 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1731 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1732 patch,
1733 offset_ + literal_offset,
1734 target_offset);
1735 break;
1736 }
1737 case LinkerPatch::Type::kTypeRelative: {
1738 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1739 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1740 patch,
1741 offset_ + literal_offset,
1742 target_offset);
1743 break;
1744 }
1745 case LinkerPatch::Type::kTypeClassTable: {
1746 uint32_t target_offset = GetClassTableEntryOffset(patch);
1747 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1748 patch,
1749 offset_ + literal_offset,
1750 target_offset);
1751 break;
1752 }
1753 case LinkerPatch::Type::kTypeBssEntry: {
1754 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1755 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1756 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1757 patch,
1758 offset_ + literal_offset,
1759 target_offset);
1760 break;
1761 }
1762 case LinkerPatch::Type::kCall: {
1763 uint32_t target_offset = GetTargetOffset(patch);
1764 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1765 break;
1766 }
1767 case LinkerPatch::Type::kMethodRelative: {
1768 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1769 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1770 patch,
1771 offset_ + literal_offset,
1772 target_offset);
1773 break;
1774 }
1775 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1776 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1777 patch,
1778 offset_ + literal_offset);
1779 break;
1780 }
1781 default: {
1782 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1783 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001784 }
1785 }
1786 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001787 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001788
1789 if (!out->WriteFully(quick_code.data(), code_size)) {
1790 ReportWriteFailure("method code", method_ref);
1791 return false;
1792 }
1793 writer_->size_code_ += code_size;
1794 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001795 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001796 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001797
1798 return true;
1799 }
1800
Igor Murashkin545412b2017-08-17 15:26:54 -07001801 size_t GetOffset() const {
1802 return offset_;
1803 }
1804
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001805 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001806 OatWriter* const writer_;
1807
1808 // Updated in VisitMethod as methods are written out.
1809 size_t offset_;
1810
1811 // Potentially varies with every different VisitMethod.
1812 // Used to determine which DexCache to use when finding ArtMethods.
1813 const DexFile* dex_file_;
1814
1815 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001816 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001817 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001818 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001819 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001820 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001821 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001822 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001823 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001824 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001825 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001826
Igor Murashkin545412b2017-08-17 15:26:54 -07001827 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001828 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001829 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001830 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001831
Mathieu Chartiere401d142015-04-22 13:56:20 -07001832 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001833 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001834 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001835 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001836 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1837 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001838 ArtMethod* method =
1839 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001840 CHECK(method != nullptr);
1841 return method;
1842 }
1843
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001844 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001845 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1846 // If there's no new compiled code, either we're compiling an app and the target method
1847 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001848 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001849 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001850 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001851 const void* oat_code_offset =
1852 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001853 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001854 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001855 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1856 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1857 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1858 target_offset = PointerToLowMemUInt32(oat_code_offset);
1859 } else {
1860 target_offset = target->IsNative()
1861 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1862 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1863 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001864 }
1865 return target_offset;
1866 }
1867
Vladimir Markocd556b02017-02-03 11:47:34 +00001868 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001869 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001870 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001871 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001872 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1873 }
1874
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001875 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001876 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001877 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001878 ObjPtr<mirror::Class> type =
1879 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001880 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001881 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001882 }
1883
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001884 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001885 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001886 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1887 patch.TargetStringIndex(),
Vladimir Markof25cc732017-03-16 16:18:15 +00001888 GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001889 DCHECK(string != nullptr);
1890 DCHECK(writer_->HasBootImage() ||
1891 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1892 return string;
1893 }
1894
Vladimir Marko65979462017-05-19 17:25:12 +01001895 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1896 DCHECK(writer_->HasBootImage());
1897 method = writer_->image_writer_->GetImageMethodAddress(method);
1898 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1899 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1900 // TODO: Clean up offset types. The target offset must be treated as signed.
1901 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1902 }
1903
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001904 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001905 DCHECK(writer_->HasBootImage());
1906 object = writer_->image_writer_->GetImageAddress(object);
1907 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1908 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1909 // TODO: Clean up offset types. The target offset must be treated as signed.
1910 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1911 }
1912
Vladimir Markof4da6752014-08-01 19:04:18 +01001913 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001914 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001915 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001916 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001917 } else {
1918 // NOTE: We're using linker patches for app->boot references when the image can
1919 // be relocated and therefore we need to emit .oat_patches. We're not using this
1920 // for app->app references, so check that the object is in the image space.
1921 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001922 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001923 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001924 uint32_t address = PointerToLowMemUInt32(object);
1925 DCHECK_LE(offset + 4, code->size());
1926 uint8_t* data = &(*code)[offset];
1927 data[0] = address & 0xffu;
1928 data[1] = (address >> 8) & 0xffu;
1929 data[2] = (address >> 16) & 0xffu;
1930 data[3] = (address >> 24) & 0xffu;
1931 }
1932
1933 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001934 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001935 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001936 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001937 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1938 // TODO: Clean up offset types.
1939 // The target_offset must be treated as signed for cross-oat patching.
1940 const void* target = reinterpret_cast<const void*>(
1941 writer_->image_writer_->GetOatDataBegin(oat_index) +
1942 static_cast<int32_t>(target_offset));
1943 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001944 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001945 DCHECK_LE(offset + 4, code->size());
1946 uint8_t* data = &(*code)[offset];
1947 data[0] = address & 0xffu;
1948 data[1] = (address >> 8) & 0xffu;
1949 data[2] = (address >> 16) & 0xffu;
1950 data[3] = (address >> 24) & 0xffu;
1951 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001952
1953 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
1954 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
1955 REQUIRES_SHARED(Locks::mutator_lock_) {
1956 DCHECK(!writer_->HasBootImage());
1957 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
1958 *patch.TargetStringDexFile(), patch.TargetStringIndex());
1959 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01001960 return GetBootImageTableEntryOffset(string_root);
1961 }
1962
1963 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
1964 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
1965 REQUIRES_SHARED(Locks::mutator_lock_) {
1966 DCHECK(!writer_->HasBootImage());
1967 const uint8_t* table_slot =
1968 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1969 DCHECK(table_slot != nullptr);
1970 return GetBootImageTableEntryOffset(table_slot);
1971 }
1972
1973 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001974 uint32_t base_offset = writer_->bss_start_;
1975 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1976 const uint8_t* const_tables_begin =
1977 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01001978 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001979 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
1980 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
1981 return base_offset + offset;
1982 }
1983 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
1984 }
1985 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
1986 UNREACHABLE();
1987 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001988};
1989
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001990class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1991 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001992 WriteMapMethodVisitor(OatWriter* writer,
1993 OutputStream* out,
1994 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001995 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001996 : OatDexMethodVisitor(writer, relative_offset),
1997 out_(out),
1998 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001999
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002000 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002001 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002002 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2003
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002004 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002005 size_t file_offset = file_offset_;
2006 OutputStream* out = out_;
2007
Mingyao Yang063fc772016-08-02 11:02:54 -07002008 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002009 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002010 ++method_offsets_index_;
2011
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002012 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2013 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2014 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002015 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002016
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002017 // If vdex is enabled, only emit the map for compiled code. The quickening info
2018 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002019 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002020 // Transform map_offset to actual oat data offset.
2021 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2022 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002023 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002024
2025 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2026 size_t map_size = map.size() * sizeof(map[0]);
2027 if (map_offset == offset_) {
2028 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002029 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002030 ReportWriteFailure(it);
2031 return false;
2032 }
2033 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002034 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002035 }
2036 DCHECK_OFFSET_();
2037 }
2038
2039 return true;
2040 }
2041
2042 private:
2043 OutputStream* const out_;
2044 size_t const file_offset_;
2045
2046 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002047 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002048 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002049 }
2050};
2051
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002052class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2053 public:
2054 WriteMethodInfoVisitor(OatWriter* writer,
2055 OutputStream* out,
2056 const size_t file_offset,
2057 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002058 : OatDexMethodVisitor(writer, relative_offset),
2059 out_(out),
2060 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002061
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002062 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002063 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2064 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2065
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002066 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002067 size_t file_offset = file_offset_;
2068 OutputStream* out = out_;
2069 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2070 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2071 ++method_offsets_index_;
2072 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2073 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2074 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2075 << dex_file_->PrettyMethod(it.GetMemberIndex());
2076 if (map_offset != 0u) {
2077 // Transform map_offset to actual oat data offset.
2078 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2079 DCHECK_NE(map_offset, 0u);
2080 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2081
2082 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2083 size_t map_size = map.size() * sizeof(map[0]);
2084 if (map_offset == offset_) {
2085 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2086 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2087 ReportWriteFailure(it);
2088 return false;
2089 }
2090 offset_ += map_size;
2091 }
2092 }
2093 DCHECK_OFFSET_();
2094 }
2095
2096 return true;
2097 }
2098
2099 private:
2100 OutputStream* const out_;
2101 size_t const file_offset_;
2102
2103 void ReportWriteFailure(const ClassDataItemIterator& it) {
2104 PLOG(ERROR) << "Failed to write map for "
2105 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2106 }
2107};
2108
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002109// Visit all methods from all classes in all dex files with the specified visitor.
2110bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2111 for (const DexFile* dex_file : *dex_files_) {
2112 const size_t class_def_count = dex_file->NumClassDefs();
2113 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2114 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2115 return false;
2116 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002117 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002118 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2119 const uint8_t* class_data = dex_file->GetClassData(class_def);
2120 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2121 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002122 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002123 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002124 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002125 if (!visitor->VisitMethod(class_def_method_index, it)) {
2126 return false;
2127 }
2128 ++class_def_method_index;
2129 it.Next();
2130 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002131 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002132 }
2133 }
2134 if (UNLIKELY(!visitor->EndClass())) {
2135 return false;
2136 }
2137 }
2138 }
2139 return true;
2140}
2141
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002142size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2143 const InstructionSetFeatures* instruction_set_features,
2144 uint32_t num_dex_files,
2145 SafeMap<std::string, std::string>* key_value_store) {
2146 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2147 oat_header_.reset(OatHeader::Create(instruction_set,
2148 instruction_set_features,
2149 num_dex_files,
2150 key_value_store));
2151 size_oat_header_ += sizeof(OatHeader);
2152 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002153 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002154}
2155
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002156size_t OatWriter::InitClassOffsets(size_t offset) {
2157 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002158 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002159 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2160 if (!oat_dex_file.class_offsets_.empty()) {
2161 // Class offsets are required to be 4 byte aligned.
2162 offset = RoundUp(offset, 4u);
2163 oat_dex_file.class_offsets_offset_ = offset;
2164 offset += oat_dex_file.GetClassOffsetsRawSize();
2165 DCHECK_ALIGNED(offset, 4u);
2166 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002167 }
2168 return offset;
2169}
2170
Brian Carlstrom389efb02012-01-11 12:06:26 -08002171size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002172 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002173 InitOatClassesMethodVisitor visitor(this, offset);
2174 bool success = VisitDexMethods(&visitor);
2175 CHECK(success);
2176 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002177
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002178 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002179 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002180 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2181 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002182 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002183 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002184 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002185 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002186 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002187 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002188
2189 return offset;
2190}
2191
2192size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002193 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002194 return offset;
2195 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002196 {
2197 InitMapMethodVisitor visitor(this, offset);
2198 bool success = VisitDexMethods(&visitor);
2199 DCHECK(success);
2200 offset = visitor.GetOffset();
2201 }
2202 {
2203 InitMethodInfoVisitor visitor(this, offset);
2204 bool success = VisitDexMethods(&visitor);
2205 DCHECK(success);
2206 offset = visitor.GetOffset();
2207 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002208 return offset;
2209}
2210
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002211size_t OatWriter::InitMethodBssMappings(size_t offset) {
2212 size_t number_of_dex_files = 0u;
2213 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2214 const DexFile* dex_file = (*dex_files_)[i];
2215 auto it = bss_method_entry_references_.find(dex_file);
2216 if (it != bss_method_entry_references_.end()) {
2217 const BitVector& method_indexes = it->second;
2218 ++number_of_dex_files;
2219 // If there are any classes, the class offsets allocation aligns the offset
2220 // and we cannot have method bss mappings without class offsets.
2221 static_assert(alignof(MethodBssMapping) == 4u, "MethodBssMapping alignment check.");
2222 DCHECK_ALIGNED(offset, 4u);
2223 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2224
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01002225 MethodBssMappingEncoder encoder(
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002226 GetInstructionSetPointerSize(oat_header_->GetInstructionSet()));
2227 size_t number_of_entries = 0u;
2228 bool first_index = true;
2229 for (uint32_t method_index : method_indexes.Indexes()) {
2230 uint32_t bss_offset = bss_method_entries_.Get(MethodReference(dex_file, method_index));
2231 if (first_index || !encoder.TryMerge(method_index, bss_offset)) {
2232 encoder.Reset(method_index, bss_offset);
2233 ++number_of_entries;
2234 first_index = false;
2235 }
2236 }
2237 DCHECK_NE(number_of_entries, 0u);
2238 offset += MethodBssMapping::ComputeSize(number_of_entries);
2239 }
2240 }
2241 // Check that all dex files targeted by method bss entries are in `*dex_files_`.
2242 CHECK_EQ(number_of_dex_files, bss_method_entry_references_.size());
2243 return offset;
2244}
2245
2246size_t OatWriter::InitOatDexFiles(size_t offset) {
2247 // Initialize offsets of oat dex files.
2248 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2249 oat_dex_file.offset_ = offset;
2250 offset += oat_dex_file.SizeOf();
2251 }
2252 return offset;
2253}
2254
Brian Carlstrome24fa612011-09-29 00:53:55 -07002255size_t OatWriter::InitOatCode(size_t offset) {
2256 // calculate the offsets within OatHeader to executable code
2257 size_t old_offset = offset;
2258 // required to be on a new page boundary
2259 offset = RoundUp(offset, kPageSize);
2260 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002261 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002262 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2263 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2264 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002265 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002266 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002267 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2268 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002269
Vladimir Marko1b404a82017-09-01 13:35:26 +01002270 #define DO_TRAMPOLINE(field, fn_name) \
2271 offset = CompiledCode::AlignCode(offset, instruction_set); \
2272 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2273 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2274 (field) = compiler_driver_->Create ## fn_name(); \
2275 if (generate_debug_info) { \
2276 debug::MethodDebugInfo info = {}; \
2277 info.trampoline_name = #fn_name; \
2278 info.isa = instruction_set; \
2279 info.is_code_address_text_relative = true; \
2280 /* Use the code offset rather than the `adjusted_offset`. */ \
2281 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2282 info.code_size = (field)->size(); \
2283 method_info_.push_back(std::move(info)); \
2284 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002285 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002286
Ian Rogers848871b2013-08-05 10:56:33 -07002287 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002288 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002289 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002290 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2291 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002292
Ian Rogers848871b2013-08-05 10:56:33 -07002293 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002294 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002295 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002296 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002297 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002298 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002299 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002300 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002301 return offset;
2302}
2303
2304size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002305 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002306 if (kOatWriterDebugOatCodeLayout) {
2307 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2308 << this << "), "
2309 << "compilation is disabled";
2310 }
2311
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002312 return offset;
2313 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002314 bool success = false;
2315
2316 {
2317 ScopedObjectAccess soa(Thread::Current());
2318
2319 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2320 success = VisitDexMethods(&layout_code_visitor);
2321 DCHECK(success);
2322
2323 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2324 this,
2325 offset,
2326 layout_code_visitor.ReleaseOrderedMethods());
2327 success = layout_reserve_code_visitor.Visit();
2328 DCHECK(success);
2329 offset = layout_reserve_code_visitor.GetOffset();
2330
2331 // Save the method order because the WriteCodeMethodVisitor will need this
2332 // order again.
2333 DCHECK(ordered_methods_ == nullptr);
2334 ordered_methods_.reset(
2335 new OrderedMethodList(
2336 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2337
2338 if (kOatWriterDebugOatCodeLayout) {
2339 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2340 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2341 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2342 LOG(INFO) << pretty_name
2343 << "@ offset "
2344 << relative_patcher_->GetOffset(ordered_method.method_reference)
2345 << " X hotness "
2346 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2347 }
2348 }
2349 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002350
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002351 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002352 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002353 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002354 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002355 DCHECK(success);
2356 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002357 }
Logan Chien8b977d32012-02-21 19:14:55 +08002358
Brian Carlstrome24fa612011-09-29 00:53:55 -07002359 return offset;
2360}
2361
Vladimir Markoaad75c62016-10-03 08:46:48 +00002362void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002363 {
2364 InitBssLayoutMethodVisitor visitor(this);
2365 bool success = VisitDexMethods(&visitor);
2366 DCHECK(success);
2367 }
2368
2369 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002370 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002371 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002372 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002373 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002374 if (!map_boot_image_tables_to_bss_ &&
2375 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002376 bss_type_entries_.empty() &&
2377 bss_string_entries_.empty()) {
2378 // Nothing to put to the .bss section.
2379 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002380 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002381
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002382 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002383 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002384 if (map_boot_image_tables_to_bss_) {
2385 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2386 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2387 }
2388 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002389
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002390 bss_methods_offset_ = bss_size_;
2391
2392 // Prepare offsets for .bss ArtMethod entries.
2393 for (auto& entry : bss_method_entries_) {
2394 DCHECK_EQ(entry.second, 0u);
2395 entry.second = bss_size_;
2396 bss_size_ += static_cast<size_t>(pointer_size);
2397 }
2398
Vladimir Markoaad75c62016-10-03 08:46:48 +00002399 bss_roots_offset_ = bss_size_;
2400
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002401 // Prepare offsets for .bss Class entries.
2402 for (auto& entry : bss_type_entries_) {
2403 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002404 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002405 bss_size_ += sizeof(GcRoot<mirror::Class>);
2406 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002407 // Prepare offsets for .bss String entries.
2408 for (auto& entry : bss_string_entries_) {
2409 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002410 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002411 bss_size_ += sizeof(GcRoot<mirror::String>);
2412 }
2413}
2414
David Srbeckybc90fd02015-04-22 19:40:27 +01002415bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002416 CHECK(write_state_ == WriteState::kWriteRoData);
2417
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002418 size_t file_offset = oat_data_offset_;
2419 off_t current_offset = out->Seek(0, kSeekCurrent);
2420 if (current_offset == static_cast<off_t>(-1)) {
2421 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2422 }
2423 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2424 size_t relative_offset = current_offset - file_offset;
2425
Vladimir Markoe079e212016-05-25 12:49:49 +01002426 // Wrap out to update checksum with each write.
2427 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2428 out = &checksum_updating_out;
2429
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002430 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2431 if (relative_offset == 0) {
2432 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002433 return false;
2434 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002435
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002436 relative_offset = WriteClasses(out, file_offset, relative_offset);
2437 if (relative_offset == 0) {
2438 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002439 return false;
2440 }
2441
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002442 relative_offset = WriteMethodBssMappings(out, file_offset, relative_offset);
2443 if (relative_offset == 0) {
2444 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002445 return false;
2446 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002447
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002448 relative_offset = WriteMaps(out, file_offset, relative_offset);
2449 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002450 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2451 return false;
2452 }
2453
2454 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2455 if (relative_offset == 0) {
2456 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002457 return false;
2458 }
2459
David Srbeckybc90fd02015-04-22 19:40:27 +01002460 // Write padding.
2461 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2462 relative_offset += size_executable_offset_alignment_;
2463 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2464 size_t expected_file_offset = file_offset + relative_offset;
2465 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2466 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2467 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2468 return 0;
2469 }
2470 DCHECK_OFFSET();
2471
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002472 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002473 return true;
2474}
2475
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002476class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
2477 public:
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002478 WriteQuickeningInfoMethodVisitor(OatWriter* writer,
2479 OutputStream* out,
2480 uint32_t offset,
2481 SafeMap<const uint8_t*, uint32_t>* offset_map)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002482 : DexMethodVisitor(writer, offset),
2483 out_(out),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002484 written_bytes_(0u),
2485 offset_map_(offset_map) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002486
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002487 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it)
2488 OVERRIDE {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002489 uint32_t method_idx = it.GetMemberIndex();
2490 CompiledMethod* compiled_method =
2491 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
2492
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002493 if (HasQuickeningInfo(compiled_method)) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002494 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002495 // Deduplication is already done on a pointer basis by the compiler driver,
2496 // so we can simply compare the pointers to find out if things are duplicated.
2497 if (offset_map_->find(map.data()) == offset_map_->end()) {
2498 uint32_t length = map.size() * sizeof(map.front());
2499 offset_map_->Put(map.data(), written_bytes_);
2500 if (!out_->WriteFully(&length, sizeof(length)) ||
2501 !out_->WriteFully(map.data(), length)) {
2502 PLOG(ERROR) << "Failed to write quickening info for "
2503 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to "
2504 << out_->GetLocation();
2505 return false;
2506 }
2507 written_bytes_ += sizeof(length) + length;
2508 offset_ += sizeof(length) + length;
2509 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002510 }
2511
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002512 return true;
2513 }
2514
2515 size_t GetNumberOfWrittenBytes() const {
2516 return written_bytes_;
2517 }
2518
2519 private:
2520 OutputStream* const out_;
2521 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002522 // Maps quickening map to its offset in the file.
2523 SafeMap<const uint8_t*, uint32_t>* offset_map_;
2524};
2525
2526class OatWriter::WriteQuickeningIndicesMethodVisitor {
2527 public:
2528 WriteQuickeningIndicesMethodVisitor(OutputStream* out,
2529 uint32_t indices_offset,
2530 const SafeMap<const uint8_t*, uint32_t>& offset_map,
2531 std::vector<uint32_t>* dex_files_offset)
2532 : out_(out),
2533 indices_offset_(indices_offset),
2534 written_bytes_(0u),
2535 dex_files_offset_(dex_files_offset),
2536 offset_map_(offset_map) {}
2537
2538 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files, const CompilerDriver& driver) {
2539 for (const DexFile* dex_file : dex_files) {
2540 // Record the offset for this current dex file. It will be written in the vdex file
2541 // later.
2542 dex_files_offset_->push_back(indices_offset_ + GetNumberOfWrittenBytes());
2543 const size_t class_def_count = dex_file->NumClassDefs();
2544 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2545 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2546 const uint8_t* class_data = dex_file->GetClassData(class_def);
2547 if (class_data == nullptr) {
2548 continue;
2549 }
2550 for (ClassDataItemIterator class_it(*dex_file, class_data);
2551 class_it.HasNext();
2552 class_it.Next()) {
2553 if (!class_it.IsAtMethod()) {
2554 continue;
2555 }
2556 uint32_t method_idx = class_it.GetMemberIndex();
2557 CompiledMethod* compiled_method =
2558 driver.GetCompiledMethod(MethodReference(dex_file, method_idx));
2559 if (HasQuickeningInfo(compiled_method)) {
2560 uint32_t code_item_offset = class_it.GetMethodCodeItemOffset();
2561 uint32_t offset = offset_map_.Get(compiled_method->GetVmapTable().data());
2562 if (!out_->WriteFully(&code_item_offset, sizeof(code_item_offset)) ||
2563 !out_->WriteFully(&offset, sizeof(offset))) {
2564 PLOG(ERROR) << "Failed to write quickening info for "
2565 << dex_file->PrettyMethod(method_idx) << " to "
2566 << out_->GetLocation();
2567 return false;
2568 }
2569 written_bytes_ += sizeof(code_item_offset) + sizeof(offset);
2570 }
2571 }
2572 }
2573 }
2574 return true;
2575 }
2576
2577 size_t GetNumberOfWrittenBytes() const {
2578 return written_bytes_;
2579 }
2580
2581 private:
2582 OutputStream* const out_;
2583 const uint32_t indices_offset_;
2584 size_t written_bytes_;
2585 std::vector<uint32_t>* dex_files_offset_;
2586 // Maps quickening map to its offset in the file.
2587 const SafeMap<const uint8_t*, uint32_t>& offset_map_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002588};
2589
2590bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002591 size_t initial_offset = vdex_size_;
2592 size_t start_offset = RoundUp(initial_offset, 4u);
2593
2594 vdex_size_ = start_offset;
2595 vdex_quickening_info_offset_ = vdex_size_;
2596 size_quickening_info_alignment_ = start_offset - initial_offset;
2597
2598 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2599 if (actual_offset != static_cast<off_t>(start_offset)) {
2600 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2601 << " Expected: " << start_offset
2602 << " Output: " << vdex_out->GetLocation();
2603 return false;
2604 }
2605
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002606 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002607 std::vector<uint32_t> dex_files_indices;
2608 SafeMap<const uint8_t*, uint32_t> offset_map;
2609 WriteQuickeningInfoMethodVisitor visitor1(this, vdex_out, start_offset, &offset_map);
2610 if (!VisitDexMethods(&visitor1)) {
2611 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2612 return false;
2613 }
2614
2615 WriteQuickeningIndicesMethodVisitor visitor2(vdex_out,
2616 visitor1.GetNumberOfWrittenBytes(),
2617 offset_map,
2618 &dex_files_indices);
2619 if (!visitor2.VisitDexMethods(*dex_files_, *compiler_driver_)) {
2620 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2621 return false;
2622 }
2623
2624 DCHECK_EQ(dex_files_->size(), dex_files_indices.size());
2625 if (!vdex_out->WriteFully(
2626 dex_files_indices.data(), sizeof(dex_files_indices[0]) * dex_files_indices.size())) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002627 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2628 return false;
2629 }
2630
2631 if (!vdex_out->Flush()) {
2632 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2633 << " File: " << vdex_out->GetLocation();
2634 return false;
2635 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002636 size_quickening_info_ = visitor1.GetNumberOfWrittenBytes() +
2637 visitor2.GetNumberOfWrittenBytes() +
2638 dex_files_->size() * sizeof(uint32_t);
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002639 } else {
2640 // We know we did not quicken.
2641 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002642 }
2643
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002644 vdex_size_ += size_quickening_info_;
2645 return true;
2646}
2647
David Brazdil5d5a36b2016-09-14 15:34:10 +01002648bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002649 if (verifier_deps == nullptr) {
2650 // Nothing to write. Record the offset, but no need
2651 // for alignment.
2652 vdex_verifier_deps_offset_ = vdex_size_;
2653 return true;
2654 }
2655
2656 size_t initial_offset = vdex_size_;
2657 size_t start_offset = RoundUp(initial_offset, 4u);
2658
2659 vdex_size_ = start_offset;
2660 vdex_verifier_deps_offset_ = vdex_size_;
2661 size_verifier_deps_alignment_ = start_offset - initial_offset;
2662
2663 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2664 if (actual_offset != static_cast<off_t>(start_offset)) {
2665 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2666 << " Expected: " << start_offset
2667 << " Output: " << vdex_out->GetLocation();
2668 return false;
2669 }
2670
2671 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002672 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002673
2674 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2675 PLOG(ERROR) << "Failed to write verifier deps."
2676 << " File: " << vdex_out->GetLocation();
2677 return false;
2678 }
2679 if (!vdex_out->Flush()) {
2680 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2681 << " File: " << vdex_out->GetLocation();
2682 return false;
2683 }
2684
2685 size_verifier_deps_ = buffer.size();
2686 vdex_size_ += size_verifier_deps_;
2687 return true;
2688}
2689
David Srbeckybc90fd02015-04-22 19:40:27 +01002690bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002691 CHECK(write_state_ == WriteState::kWriteText);
2692
Vladimir Markoe079e212016-05-25 12:49:49 +01002693 // Wrap out to update checksum with each write.
2694 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2695 out = &checksum_updating_out;
2696
Vladimir Marko944da602016-02-19 12:27:55 +00002697 SetMultiOatRelativePatcherAdjustment();
2698
David Srbeckybc90fd02015-04-22 19:40:27 +01002699 const size_t file_offset = oat_data_offset_;
2700 size_t relative_offset = oat_header_->GetExecutableOffset();
2701 DCHECK_OFFSET();
2702
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002703 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002704 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002705 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002706 return false;
2707 }
2708
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002709 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2710 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002711 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002712 return false;
2713 }
2714
Vladimir Markof4da6752014-08-01 19:04:18 +01002715 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002716 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002717 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2718 return false;
2719 }
2720
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002721 if (kIsDebugBuild) {
2722 uint32_t size_total = 0;
2723 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002724 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2725 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002726
David Brazdil7b49e6c2016-09-01 11:06:18 +01002727 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002728 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002729 DO_STAT(size_dex_file_alignment_);
2730 DO_STAT(size_executable_offset_alignment_);
2731 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002732 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002733 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002734 DO_STAT(size_verifier_deps_);
2735 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002736 DO_STAT(size_quickening_info_);
2737 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002738 DO_STAT(size_interpreter_to_interpreter_bridge_);
2739 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2740 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002741 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002742 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002743 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002744 DO_STAT(size_quick_to_interpreter_bridge_);
2745 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002746 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002747 DO_STAT(size_code_);
2748 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002749 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002750 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002751 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002752 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002753 DO_STAT(size_oat_dex_file_location_size_);
2754 DO_STAT(size_oat_dex_file_location_data_);
2755 DO_STAT(size_oat_dex_file_location_checksum_);
2756 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002757 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002758 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002759 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2760 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2761 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002762 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002763 DO_STAT(size_oat_lookup_table_alignment_);
2764 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002765 DO_STAT(size_oat_class_offsets_alignment_);
2766 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002767 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002768 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002769 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002770 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002771 DO_STAT(size_method_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002772 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002773
David Brazdil7b49e6c2016-09-01 11:06:18 +01002774 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2775
2776 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2777 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002778 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002779
David Brazdil7b49e6c2016-09-01 11:06:18 +01002780 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2781 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002782
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002783 write_state_ = WriteState::kWriteHeader;
2784 return true;
2785}
2786
2787bool OatWriter::WriteHeader(OutputStream* out,
2788 uint32_t image_file_location_oat_checksum,
2789 uintptr_t image_file_location_oat_begin,
2790 int32_t image_patch_delta) {
2791 CHECK(write_state_ == WriteState::kWriteHeader);
2792
2793 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2794 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002795 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002796 CHECK_EQ(image_patch_delta, 0);
2797 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2798 } else {
2799 CHECK_ALIGNED(image_patch_delta, kPageSize);
2800 oat_header_->SetImagePatchDelta(image_patch_delta);
2801 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002802 oat_header_->UpdateChecksumWithHeaderData();
2803
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002804 const size_t file_offset = oat_data_offset_;
2805
2806 off_t current_offset = out->Seek(0, kSeekCurrent);
2807 if (current_offset == static_cast<off_t>(-1)) {
2808 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2809 return false;
2810 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002811 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002812 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2813 return false;
2814 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002815 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002816
2817 // Flush all other data before writing the header.
2818 if (!out->Flush()) {
2819 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2820 return false;
2821 }
2822 // Write the header.
2823 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002824 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002825 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2826 return false;
2827 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002828 // Flush the header data.
2829 if (!out->Flush()) {
2830 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002831 return false;
2832 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002833
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002834 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2835 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2836 return false;
2837 }
2838 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2839
2840 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002841 return true;
2842}
2843
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002844size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002845 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2846 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002847 // Class offsets are required to be 4 byte aligned.
2848 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
2849 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
2850 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
2851 return 0u;
2852 }
2853 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00002854 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002855 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002856 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002857 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002858 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002859 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002860 }
2861 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002862 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002863}
2864
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002865size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002866 const bool may_have_compiled = MayHaveCompiledMethods();
2867 if (may_have_compiled) {
2868 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
2869 }
2870 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002871 // If there are any classes, the class offsets allocation aligns the offset.
2872 DCHECK_ALIGNED(relative_offset, 4u);
2873 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002874 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002875 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00002876 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002877 relative_offset += oat_class_headers_[i].SizeOf();
2878 if (may_have_compiled) {
2879 if (!oat_classes_[i].Write(this, out)) {
2880 return 0u;
2881 }
2882 relative_offset += oat_classes_[i].SizeOf();
2883 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002884 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002885 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002886}
2887
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002888size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002889 {
2890 size_t vmap_tables_offset = relative_offset;
2891 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2892 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2893 return 0;
2894 }
2895 relative_offset = visitor.GetOffset();
2896 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002897 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002898 {
2899 size_t method_infos_offset = relative_offset;
2900 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
2901 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2902 return 0;
2903 }
2904 relative_offset = visitor.GetOffset();
2905 size_method_info_ = relative_offset - method_infos_offset;
2906 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002907
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002908 return relative_offset;
2909}
2910
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002911size_t OatWriter::WriteMethodBssMappings(OutputStream* out,
2912 size_t file_offset,
2913 size_t relative_offset) {
2914 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
2915
2916 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2917 const DexFile* dex_file = (*dex_files_)[i];
2918 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2919 auto it = bss_method_entry_references_.find(dex_file);
2920 if (it != bss_method_entry_references_.end()) {
2921 const BitVector& method_indexes = it->second;
2922 // If there are any classes, the class offsets allocation aligns the offset
2923 // and we cannot have method bss mappings without class offsets.
2924 static_assert(alignof(MethodBssMapping) == sizeof(uint32_t),
2925 "MethodBssMapping alignment check.");
2926 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
2927
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01002928 MethodBssMappingEncoder encoder(
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002929 GetInstructionSetPointerSize(oat_header_->GetInstructionSet()));
2930 // Allocate a sufficiently large MethodBssMapping.
2931 size_t number_of_method_indexes = method_indexes.NumSetBits();
2932 DCHECK_NE(number_of_method_indexes, 0u);
2933 size_t max_mappings_size = MethodBssMapping::ComputeSize(number_of_method_indexes);
2934 DCHECK_ALIGNED(max_mappings_size, sizeof(uint32_t));
2935 std::unique_ptr<uint32_t[]> storage(new uint32_t[max_mappings_size / sizeof(uint32_t)]);
2936 MethodBssMapping* mappings = new(storage.get()) MethodBssMapping(number_of_method_indexes);
2937 mappings->ClearPadding();
2938 // Encode the MethodBssMapping.
2939 auto init_it = mappings->begin();
2940 bool first_index = true;
2941 for (uint32_t method_index : method_indexes.Indexes()) {
2942 size_t bss_offset = bss_method_entries_.Get(MethodReference(dex_file, method_index));
2943 if (first_index) {
2944 first_index = false;
2945 encoder.Reset(method_index, bss_offset);
2946 } else if (!encoder.TryMerge(method_index, bss_offset)) {
2947 *init_it = encoder.GetEntry();
2948 ++init_it;
2949 encoder.Reset(method_index, bss_offset);
2950 }
2951 }
2952 // Store the last entry and shrink the mapping to the actual size.
2953 *init_it = encoder.GetEntry();
2954 ++init_it;
2955 DCHECK(init_it <= mappings->end());
2956 mappings->SetSize(std::distance(mappings->begin(), init_it));
2957 size_t mappings_size = MethodBssMapping::ComputeSize(mappings->size());
2958
2959 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
2960 DCHECK_OFFSET();
2961 if (!out->WriteFully(storage.get(), mappings_size)) {
2962 return 0u;
2963 }
2964 size_method_bss_mappings_ += mappings_size;
2965 relative_offset += mappings_size;
2966 } else {
2967 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
2968 }
2969 }
2970 return relative_offset;
2971}
2972
2973size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
2974 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2975
2976 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2977 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2978 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
2979 DCHECK_OFFSET();
2980
2981 // Write OatDexFile.
2982 if (!oat_dex_file->Write(this, out)) {
2983 return 0u;
2984 }
2985 relative_offset += oat_dex_file->SizeOf();
2986 }
2987
2988 return relative_offset;
2989}
2990
2991size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00002992 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002993 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002994
Ian Rogers848871b2013-08-05 10:56:33 -07002995 #define DO_TRAMPOLINE(field) \
2996 do { \
2997 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
2998 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08002999 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003000 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003001 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003002 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003003 return false; \
3004 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003005 size_ ## field += (field)->size(); \
3006 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003007 DCHECK_OFFSET(); \
3008 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003009
Ian Rogers848871b2013-08-05 10:56:33 -07003010 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003011 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003012 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003013 DO_TRAMPOLINE(quick_resolution_trampoline_);
3014 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3015 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003016 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003017 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003018}
3019
Ian Rogers3d504072014-03-01 09:16:49 -08003020size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003021 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003022 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003023 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3024 // As with InitOatCodeDexFiles, also skip the writer if
3025 // compilation was disabled.
3026 if (kOatWriterDebugOatCodeLayout) {
3027 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3028 << this << "), "
3029 << "compilation is disabled";
3030 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003031
Igor Murashkin545412b2017-08-17 15:26:54 -07003032 return relative_offset;
3033 }
3034 ScopedObjectAccess soa(Thread::Current());
3035 DCHECK(ordered_methods_ != nullptr);
3036 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3037 std::move(ordered_methods_);
3038 WriteCodeMethodVisitor visitor(this,
3039 out,
3040 file_offset,
3041 relative_offset,
3042 std::move(*ordered_methods_ptr));
3043 if (UNLIKELY(!visitor.Visit())) {
3044 return 0;
3045 }
3046 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003047
Vladimir Markob163bb72015-03-31 21:49:49 +01003048 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3049 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3050 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3051
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003052 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003053}
3054
Vladimir Marko944da602016-02-19 12:27:55 +00003055bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003056 // Get the elf file offset of the oat file.
3057 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3058 if (raw_file_offset == static_cast<off_t>(-1)) {
3059 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3060 return false;
3061 }
3062 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3063 return true;
3064}
3065
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003066bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
3067 // Read the dex file header and perform minimal verification.
3068 uint8_t raw_header[sizeof(DexFile::Header)];
3069 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
3070 PLOG(ERROR) << "Failed to read dex file header. Actual: "
3071 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3072 return false;
3073 }
3074 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
3075 return false;
3076 }
3077
3078 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
3079 oat_dex_file->dex_file_size_ = header->file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003080 return true;
3081}
3082
3083bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
Mathieu Chartiercf76bf82017-09-25 16:22:36 -07003084 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
Mathieu Chartier292567e2017-10-12 13:24:38 -07003085 if (!valid_standard_dex_magic) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003086 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
3087 return false;
3088 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -07003089 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003090 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
3091 return false;
3092 }
3093 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
3094 if (header->file_size_ < sizeof(DexFile::Header)) {
3095 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
3096 << " File: " << location;
3097 return false;
3098 }
3099 return true;
3100}
3101
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003102bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003103 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003104
David Brazdil7b49e6c2016-09-01 11:06:18 +01003105 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003106
3107 // Write dex files.
3108 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003109 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003110 return false;
3111 }
3112 }
3113
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003114 CloseSources();
3115 return true;
3116}
3117
3118void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003119 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3120 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3121 }
3122 zipped_dex_files_.clear();
3123 zip_archives_.clear();
3124 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003125}
3126
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003127bool OatWriter::WriteDexFile(OutputStream* out,
3128 File* file,
3129 OatDexFile* oat_dex_file,
3130 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003131 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003132 return false;
3133 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003134 if (profile_compilation_info_ != nullptr ||
3135 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01003136 CHECK(!update_input_vdex) << "We should never update the input vdex when doing dexlayout";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003137 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3138 return false;
3139 }
3140 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003141 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003142 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003143 return false;
3144 }
3145 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003146 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003147 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003148 return false;
3149 }
3150 } else {
3151 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003152 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003153 return false;
3154 }
3155 }
3156
3157 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003158 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3159 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003160 size_dex_file_ += oat_dex_file->dex_file_size_;
3161 return true;
3162}
3163
3164bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3165 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003166 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003167 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003168 size_t file_offset = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003169 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003170
3171 // Seek to the start of the dex file and flush any pending operations in the stream.
3172 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003173 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3174 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003175 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003176 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003177 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3178 return false;
3179 }
3180 if (!out->Flush()) {
3181 PLOG(ERROR) << "Failed to flush before writing dex file."
3182 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3183 return false;
3184 }
3185 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003186 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003187 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003188 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003189 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3190 return false;
3191 }
3192
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003193 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003194 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003195 return true;
3196}
3197
Jeff Hao608f2ce2016-10-19 11:17:11 -07003198bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3199 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3200 std::string error_msg;
3201 std::string location(oat_dex_file->GetLocation());
3202 std::unique_ptr<const DexFile> dex_file;
3203 if (oat_dex_file->source_.IsZipEntry()) {
3204 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3205 std::unique_ptr<MemMap> mem_map(
3206 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003207 if (mem_map == nullptr) {
3208 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3209 return false;
3210 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003211 dex_file = DexFileLoader::Open(location,
3212 zip_entry->GetCrc32(),
3213 std::move(mem_map),
3214 /* verify */ true,
3215 /* verify_checksum */ true,
3216 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003217 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003218 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003219 int dup_fd = dup(raw_file->Fd());
3220 if (dup_fd < 0) {
3221 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3222 return false;
3223 }
Nicolas Geoffray095c6c92017-10-19 13:59:55 +01003224 dex_file = DexFileLoader::OpenDex(
3225 dup_fd, location, /* verify */ true, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003226 } else {
3227 // The source data is a vdex file.
3228 CHECK(oat_dex_file->source_.IsRawData())
3229 << static_cast<size_t>(oat_dex_file->source_.GetType());
3230 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3231 // Note: The raw data has already been checked to contain the header
3232 // and all the data that the header specifies as the file size.
3233 DCHECK(raw_dex_file != nullptr);
3234 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3235 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3236 // Since the source may have had its layout changed, or may be quickened, don't verify it.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003237 dex_file = DexFileLoader::Open(raw_dex_file,
3238 header->file_size_,
3239 location,
3240 oat_dex_file->dex_file_location_checksum_,
3241 nullptr,
3242 /* verify */ false,
3243 /* verify_checksum */ false,
3244 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003245 }
Jeff Haode197542017-02-03 10:48:13 -08003246 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003247 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003248 return false;
3249 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003250 Options options;
3251 options.output_to_memmap_ = true;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003252 options.compact_dex_level_ = compact_dex_level_;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003253 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
3254 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
3255 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003256 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003257 return false;
3258 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07003259 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
Jeff Hao608f2ce2016-10-19 11:17:11 -07003260 return true;
3261}
3262
David Brazdil7b49e6c2016-09-01 11:06:18 +01003263bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003264 File* file,
3265 OatDexFile* oat_dex_file,
3266 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003267 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003268 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003269
3270 // Extract the dex file and get the extracted size.
3271 std::string error_msg;
3272 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3273 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3274 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3275 return false;
3276 }
3277 if (file->Flush() != 0) {
3278 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3279 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3280 return false;
3281 }
3282 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3283 if (extracted_end == static_cast<off_t>(-1)) {
3284 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3285 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3286 return false;
3287 }
3288 if (extracted_end < static_cast<off_t>(start_offset)) {
3289 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3290 << " Start: " << start_offset
3291 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3292 return false;
3293 }
3294 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3295 if (extracted_size < sizeof(DexFile::Header)) {
3296 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3297 << extracted_size << " File: " << oat_dex_file->GetLocation();
3298 return false;
3299 }
3300
3301 // Read the dex file header and extract required data to OatDexFile.
3302 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3303 if (actual_offset != static_cast<off_t>(start_offset)) {
3304 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3305 << " Expected: " << start_offset
3306 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3307 return false;
3308 }
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003309 // Read the dex file header to get the dex file size.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003310 if (!ReadDexFileHeader(file, oat_dex_file)) {
3311 return false;
3312 }
3313 if (extracted_size < oat_dex_file->dex_file_size_) {
3314 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3315 << " file size from header: " << oat_dex_file->dex_file_size_
3316 << " File: " << oat_dex_file->GetLocation();
3317 return false;
3318 }
3319
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003320 // Seek both file and stream to the end offset.
3321 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3322 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3323 if (actual_offset != static_cast<off_t>(end_offset)) {
3324 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3325 << " Expected: " << end_offset
3326 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3327 return false;
3328 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003329 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003330 if (actual_offset != static_cast<off_t>(end_offset)) {
3331 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3332 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3333 return false;
3334 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003335 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003336 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3337 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3338 return false;
3339 }
3340
3341 // If we extracted more than the size specified in the header, truncate the file.
3342 if (extracted_size > oat_dex_file->dex_file_size_) {
3343 if (file->SetLength(end_offset) != 0) {
3344 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003345 << " File: " << oat_dex_file->GetLocation()
3346 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003347 return false;
3348 }
3349 }
3350
3351 return true;
3352}
3353
David Brazdil7b49e6c2016-09-01 11:06:18 +01003354bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003355 File* file,
3356 OatDexFile* oat_dex_file,
3357 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003358 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003359 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003360
3361 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3362 if (input_offset != static_cast<off_t>(0)) {
3363 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3364 << " Expected: 0"
3365 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3366 return false;
3367 }
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003368 // Read the dex file header to get the dex file size.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003369 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
3370 return false;
3371 }
3372
3373 // Copy the input dex file using sendfile().
3374 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3375 PLOG(ERROR) << "Failed to copy dex file to oat file."
3376 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3377 return false;
3378 }
3379 if (file->Flush() != 0) {
3380 PLOG(ERROR) << "Failed to flush dex file."
3381 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3382 return false;
3383 }
3384
3385 // Check file position and seek the stream to the end offset.
3386 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3387 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3388 if (actual_offset != static_cast<off_t>(end_offset)) {
3389 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3390 << " Expected: " << end_offset
3391 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3392 return false;
3393 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003394 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003395 if (actual_offset != static_cast<off_t>(end_offset)) {
3396 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3397 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3398 return false;
3399 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003400 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003401 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3402 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3403 return false;
3404 }
3405
3406 return true;
3407}
3408
David Brazdil7b49e6c2016-09-01 11:06:18 +01003409bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003410 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003411 const uint8_t* dex_file,
3412 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003413 // Note: The raw data has already been checked to contain the header
3414 // and all the data that the header specifies as the file size.
3415 DCHECK(dex_file != nullptr);
3416 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3417 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3418
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003419 if (update_input_vdex) {
3420 // The vdex already contains the dex code, no need to write it again.
3421 } else {
3422 if (!out->WriteFully(dex_file, header->file_size_)) {
3423 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3424 << " to " << out->GetLocation();
3425 return false;
3426 }
3427 if (!out->Flush()) {
3428 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3429 << " File: " << oat_dex_file->GetLocation();
3430 return false;
3431 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003432 }
3433
3434 // Update dex file size and resize class offsets in the OatDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003435 oat_dex_file->dex_file_size_ = header->file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003436 return true;
3437}
3438
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003439bool OatWriter::OpenDexFiles(
3440 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003441 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003442 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
3443 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3444 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3445
3446 if (oat_dex_files_.empty()) {
3447 // Nothing to do.
3448 return true;
3449 }
3450
3451 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003452 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003453
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003454 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003455 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3456 length,
3457 PROT_READ | PROT_WRITE,
3458 MAP_SHARED,
3459 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003460 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003461 /* low_4gb */ false,
3462 file->GetPath().c_str(),
3463 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003464 if (dex_files_map == nullptr) {
3465 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3466 << " error: " << error_msg;
3467 return false;
3468 }
3469 std::vector<std::unique_ptr<const DexFile>> dex_files;
3470 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003471 const uint8_t* raw_dex_file =
3472 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003473
3474 if (kIsDebugBuild) {
3475 // Sanity check our input files.
3476 // Note that ValidateDexFileHeader() logs error messages.
3477 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3478 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003479 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3480 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003481
3482 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3483 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3484 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003485 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3486 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003487 }
3488
3489 // Now, open the dex file.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003490 dex_files.emplace_back(DexFileLoader::Open(raw_dex_file,
3491 oat_dex_file.dex_file_size_,
3492 oat_dex_file.GetLocation(),
3493 oat_dex_file.dex_file_location_checksum_,
3494 /* oat_dex_file */ nullptr,
3495 verify,
3496 verify,
3497 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003498 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003499 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3500 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003501 return false;
3502 }
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003503
3504 // Set the class_offsets size now that we have easy access to the DexFile and
3505 // it has been verified in DexFileLoader::Open.
3506 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003507 }
3508
3509 *opened_dex_files_map = std::move(dex_files_map);
3510 *opened_dex_files = std::move(dex_files);
3511 return true;
3512}
3513
3514bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003515 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003516 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3517 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3518
David Brazdil7b49e6c2016-09-01 11:06:18 +01003519 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3520 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3521 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3522 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3523 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3524 return false;
3525 }
3526
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003527 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3528 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3529 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003530 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3531
3532 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3533 oat_dex_file->class_offsets_.empty()) {
3534 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003535 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003536
3537 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3538 if (table_size == 0u) {
3539 continue;
3540 }
3541
3542 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003543 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003544 const DexFile& dex_file = *opened_dex_files[i];
3545 {
3546 std::unique_ptr<TypeLookupTable> type_lookup_table =
3547 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3548 type_lookup_table_oat_dex_files_.push_back(
3549 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3550 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3551 }
3552 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003553
3554 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003555 size_t initial_offset = oat_size_;
3556 size_t rodata_offset = RoundUp(initial_offset, 4);
3557 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003558
3559 if (padding_size != 0u) {
3560 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003561 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003562 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3563 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003564 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003565 return false;
3566 }
3567 }
3568
3569 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003570 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003571 DCHECK_EQ(table_size, table->RawDataLength());
3572
David Brazdil7b49e6c2016-09-01 11:06:18 +01003573 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003574 PLOG(ERROR) << "Failed to write lookup table."
3575 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003576 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003577 return false;
3578 }
3579
3580 oat_dex_file->lookup_table_offset_ = rodata_offset;
3581
David Brazdil7b49e6c2016-09-01 11:06:18 +01003582 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003583 size_oat_lookup_table_ += table_size;
3584 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003585 }
3586
David Brazdil7b49e6c2016-09-01 11:06:18 +01003587 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003588 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003589 << " File: " << oat_rodata->GetLocation();
3590 return false;
3591 }
3592
3593 return true;
3594}
3595
Mathieu Chartier120aa282017-08-05 16:03:03 -07003596bool OatWriter::WriteDexLayoutSections(
3597 OutputStream* oat_rodata,
3598 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3599 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3600
3601 if (!kWriteDexLayoutInfo) {
3602 return true;;
3603 }
3604
3605 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3606 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3607 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3608 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3609 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3610 return false;
3611 }
3612
3613 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3614 size_t rodata_offset = oat_size_;
3615 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3616 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3617 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3618
3619 // Write dex layout section alignment bytes.
3620 const size_t padding_size =
3621 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3622 if (padding_size != 0u) {
3623 std::vector<uint8_t> buffer(padding_size, 0u);
3624 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3625 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3626 << " File: " << oat_dex_file->GetLocation()
3627 << " Output: " << oat_rodata->GetLocation();
3628 return false;
3629 }
3630 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3631 rodata_offset += padding_size;
3632 }
3633
3634 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3635 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3636 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3637 DCHECK(oat_dex_file != nullptr);
3638 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3639 sizeof(oat_dex_file->dex_sections_layout_))) {
3640 PLOG(ERROR) << "Failed to write dex layout sections."
3641 << " File: " << oat_dex_file->GetLocation()
3642 << " Output: " << oat_rodata->GetLocation();
3643 return false;
3644 }
3645 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3646 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3647 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3648 }
3649 oat_size_ = rodata_offset;
3650
3651 if (!oat_rodata->Flush()) {
3652 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3653 << " File: " << oat_rodata->GetLocation();
3654 return false;
3655 }
3656
3657 return true;
3658}
3659
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003660bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003661 // Write checksums
3662 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
3663 if (actual_offset != sizeof(VdexFile::Header)) {
3664 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3665 << " File: " << vdex_out->GetLocation();
3666 return false;
3667 }
3668
3669 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3670 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3671 if (!vdex_out->WriteFully(
3672 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3673 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3674 << vdex_out->GetLocation();
3675 return false;
3676 }
3677 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3678 }
3679
3680 // Write header.
3681 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003682 if (actual_offset != 0) {
3683 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3684 << " File: " << vdex_out->GetLocation();
3685 return false;
3686 }
3687
David Brazdil5d5a36b2016-09-14 15:34:10 +01003688 DCHECK_NE(vdex_dex_files_offset_, 0u);
3689 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
3690
3691 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003692 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3693 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003694
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003695 VdexFile::Header vdex_header(oat_dex_files_.size(),
3696 dex_section_size,
3697 verifier_deps_section_size,
3698 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003699 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
3700 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003701 return false;
3702 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003703 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003704
David Brazdil5d5a36b2016-09-14 15:34:10 +01003705 if (!vdex_out->Flush()) {
3706 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3707 << " File: " << vdex_out->GetLocation();
3708 return false;
3709 }
3710
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003711 return true;
3712}
3713
Vladimir Markof4da6752014-08-01 19:04:18 +01003714bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003715 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3716}
3717
3718bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003719 static const uint8_t kPadding[] = {
3720 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3721 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003722 DCHECK_LE(size, sizeof(kPadding));
3723 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003724 return false;
3725 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003726 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01003727 return true;
3728}
3729
Vladimir Marko944da602016-02-19 12:27:55 +00003730void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3731 DCHECK(dex_files_ != nullptr);
3732 DCHECK(relative_patcher_ != nullptr);
3733 DCHECK_NE(oat_data_offset_, 0u);
3734 if (image_writer_ != nullptr && !dex_files_->empty()) {
3735 // The oat data begin may not be initialized yet but the oat file offset is ready.
3736 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3737 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3738 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01003739 }
3740}
3741
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003742OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3743 DexFileSource source,
3744 CreateTypeLookupTable create_type_lookup_table)
3745 : source_(source),
3746 create_type_lookup_table_(create_type_lookup_table),
3747 dex_file_size_(0),
3748 offset_(0),
3749 dex_file_location_size_(strlen(dex_file_location)),
3750 dex_file_location_data_(dex_file_location),
3751 dex_file_location_checksum_(0u),
3752 dex_file_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003753 lookup_table_offset_(0u),
Mathieu Chartier120aa282017-08-05 16:03:03 -07003754 dex_sections_layout_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003755 class_offsets_offset_(0u),
3756 method_bss_mapping_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003757 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07003758}
3759
3760size_t OatWriter::OatDexFile::SizeOf() const {
3761 return sizeof(dex_file_location_size_)
3762 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003763 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08003764 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003765 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003766 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003767 + sizeof(method_bss_mapping_offset_)
3768 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003769}
3770
3771bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3772 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003773 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003774
Vladimir Markoe079e212016-05-25 12:49:49 +01003775 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003776 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003777 return false;
3778 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003779 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003780
Vladimir Markoe079e212016-05-25 12:49:49 +01003781 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003782 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003783 return false;
3784 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003785 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003786
Vladimir Markoe079e212016-05-25 12:49:49 +01003787 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003788 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003789 return false;
3790 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003791 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003792
Vladimir Markoe079e212016-05-25 12:49:49 +01003793 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003794 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003795 return false;
3796 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003797 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003798
Vladimir Markoe079e212016-05-25 12:49:49 +01003799 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003800 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3801 return false;
3802 }
3803 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3804
Vladimir Markoe079e212016-05-25 12:49:49 +01003805 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003806 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3807 return false;
3808 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003809 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003810
Mathieu Chartier120aa282017-08-05 16:03:03 -07003811 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
3812 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
3813 return false;
3814 }
3815 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
3816
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003817 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
3818 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
3819 return false;
3820 }
3821 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
3822
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003823 return true;
3824}
3825
3826bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003827 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003828 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
3829 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003830 return false;
3831 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003832 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003833 return true;
3834}
3835
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003836OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003837 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003838 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003839 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003840 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003841 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07003842
Brian Carlstromba150c32013-08-27 17:31:03 -07003843 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
3844
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003845 method_offsets_.resize(compiled_methods_with_code);
3846 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07003847
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003848 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
3849 // We only create this instance if there are at least some compiled.
3850 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003851 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07003852 method_bitmap_size_ = method_bitmap_->GetSizeOf();
3853 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
3854 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
3855 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003856 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07003857 method_bitmap_size_ = 0;
3858 }
3859
3860 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003861 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003862 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003863 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
3864 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003865 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003866 method_bitmap_->SetBit(i);
3867 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003868 } else {
3869 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07003870 }
3871 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003872}
3873
Brian Carlstrom265091e2013-01-30 14:08:26 -08003874size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003875 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07003876 + method_bitmap_size_
3877 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07003878}
3879
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003880bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
3881 OutputStream* out,
3882 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08003883 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01003884 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003885 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003886 return false;
3887 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003888 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003889
Vladimir Markoe079e212016-05-25 12:49:49 +01003890 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003891 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003892 return false;
3893 }
3894 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003895 return true;
3896}
Vladimir Marko49b0f452015-12-10 13:49:19 +00003897
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003898bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003899 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003900 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003901 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003902 return false;
3903 }
3904 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003905
Vladimir Markoe079e212016-05-25 12:49:49 +01003906 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003907 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003908 return false;
3909 }
3910 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
3911 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003912
Vladimir Markoe079e212016-05-25 12:49:49 +01003913 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08003914 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003915 return false;
3916 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003917 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003918 return true;
3919}
3920
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01003921const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
3922 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01003923 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01003924 uint32_t utf16_length;
3925 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
3926 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
3927 InternTable::Utf8String string(utf16_length,
3928 utf8_data,
3929 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
3930 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
3931 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
3932 auto it = table.Find(string);
3933 if (it != table.end()) {
3934 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
3935 }
3936 }
3937 LOG(FATAL) << "Did not find boot image string " << utf8_data;
3938 UNREACHABLE();
3939}
3940
Vladimir Marko94ec2db2017-09-06 17:21:03 +01003941const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
3942 dex::TypeIndex type_idx)
3943 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
3944 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
3945 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
3946 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
3947 for (const ClassTable::ClassSet& class_set : table->classes_) {
3948 auto it = class_set.Find(pair);
3949 if (it != class_set.end()) {
3950 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
3951 }
3952 }
3953 LOG(FATAL) << "Did not find boot image class " << descriptor;
3954 UNREACHABLE();
3955}
3956
Vladimir Marko74527972016-11-29 15:57:32 +00003957} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07003958} // namespace art