blob: d8671d2dd0aa46b7b487f943cecb05fe77468d6b [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Igor Murashkin545412b2017-08-17 15:26:54 -070019#include <algorithm>
Vladimir Marko9bdf1082016-01-21 12:15:52 +000020#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070021#include <zlib.h>
22
Vladimir Markoc74658b2015-03-31 10:26:41 +010023#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070025#include "base/allocator.h"
Vladimir Marko0eb882b2017-05-15 13:39:18 +010026#include "base/bit_vector-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070027#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000028#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070031#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010032#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010033#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000035#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000036#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070037#include "dex_file_loader.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070038#include "dex_file_types.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070039#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070040#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000041#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010042#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030044#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010045#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010046#include "linker/buffered_output_stream.h"
47#include "linker/file_output_stream.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010048#include "linker/linker_patch.h"
Vladimir Marko0eb882b2017-05-15 13:39:18 +010049#include "linker/method_bss_mapping_encoder.h"
Vladimir Marko944da602016-02-19 12:27:55 +000050#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000051#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/array.h"
53#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010054#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070055#include "mirror/object-inl.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070056#include "standard_dex_file.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010057#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070058#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070059#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070060#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030061#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010062#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010063#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010064#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000065#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070066
67namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000068namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070069
Vladimir Marko9bdf1082016-01-21 12:15:52 +000070namespace { // anonymous namespace
71
Mathieu Chartier120aa282017-08-05 16:03:03 -070072// If we write dex layout info in the oat file.
73static constexpr bool kWriteDexLayoutInfo = true;
74
Igor Murashkin545412b2017-08-17 15:26:54 -070075// Force the OAT method layout to be sorted-by-name instead of
76// the default (class_def_idx, method_idx).
77//
78// Otherwise if profiles are used, that will act as
79// the primary sort order.
80//
81// A bit easier to use for development since oatdump can easily
82// show that things are being re-ordered when two methods aren't adjacent.
83static constexpr bool kOatWriterForceOatCodeLayout = false;
84
85static constexpr bool kOatWriterDebugOatCodeLayout = false;
86
Vladimir Marko9bdf1082016-01-21 12:15:52 +000087typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
88
89const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
90 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
91}
92
Vladimir Markoe079e212016-05-25 12:49:49 +010093class ChecksumUpdatingOutputStream : public OutputStream {
94 public:
95 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
96 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
97
98 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
99 oat_header_->UpdateChecksum(buffer, byte_count);
100 return out_->WriteFully(buffer, byte_count);
101 }
102
103 off_t Seek(off_t offset, Whence whence) OVERRIDE {
104 return out_->Seek(offset, whence);
105 }
106
107 bool Flush() OVERRIDE {
108 return out_->Flush();
109 }
110
111 private:
112 OutputStream* const out_;
113 OatHeader* const oat_header_;
114};
115
Vladimir Marko0c737df2016-08-01 16:33:16 +0100116inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
117 // We want to align the code rather than the preheader.
118 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
119 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
120 return aligned_code_offset - unaligned_code_offset;
121}
122
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000123} // anonymous namespace
124
125// Defines the location of the raw dex file to write.
126class OatWriter::DexFileSource {
127 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800128 enum Type {
129 kNone,
130 kZipEntry,
131 kRawFile,
132 kRawData,
133 };
134
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000135 explicit DexFileSource(ZipEntry* zip_entry)
136 : type_(kZipEntry), source_(zip_entry) {
137 DCHECK(source_ != nullptr);
138 }
139
140 explicit DexFileSource(File* raw_file)
141 : type_(kRawFile), source_(raw_file) {
142 DCHECK(source_ != nullptr);
143 }
144
145 explicit DexFileSource(const uint8_t* dex_file)
146 : type_(kRawData), source_(dex_file) {
147 DCHECK(source_ != nullptr);
148 }
149
Mathieu Chartier497d5262017-02-28 20:17:30 -0800150 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000151 bool IsZipEntry() const { return type_ == kZipEntry; }
152 bool IsRawFile() const { return type_ == kRawFile; }
153 bool IsRawData() const { return type_ == kRawData; }
154
155 ZipEntry* GetZipEntry() const {
156 DCHECK(IsZipEntry());
157 DCHECK(source_ != nullptr);
158 return static_cast<ZipEntry*>(const_cast<void*>(source_));
159 }
160
161 File* GetRawFile() const {
162 DCHECK(IsRawFile());
163 DCHECK(source_ != nullptr);
164 return static_cast<File*>(const_cast<void*>(source_));
165 }
166
167 const uint8_t* GetRawData() const {
168 DCHECK(IsRawData());
169 DCHECK(source_ != nullptr);
170 return static_cast<const uint8_t*>(source_);
171 }
172
173 void Clear() {
174 type_ = kNone;
175 source_ = nullptr;
176 }
177
178 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000179 Type type_;
180 const void* source_;
181};
182
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700183// OatClassHeader is the header only part of the oat class that is required even when compilation
184// is not enabled.
185class OatWriter::OatClassHeader {
186 public:
187 OatClassHeader(uint32_t offset,
188 uint32_t num_non_null_compiled_methods,
189 uint32_t num_methods,
190 mirror::Class::Status status)
191 : status_(status),
192 offset_(offset) {
193 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
194 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
195 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
196 if (num_non_null_compiled_methods == 0) {
197 type_ = kOatClassNoneCompiled;
198 } else if (num_non_null_compiled_methods == num_methods) {
199 type_ = kOatClassAllCompiled;
200 } else {
201 type_ = kOatClassSomeCompiled;
202 }
203 }
204
205 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
206
207 static size_t SizeOf() {
208 return sizeof(status_) + sizeof(type_);
209 }
210
211 // Data to write.
212 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
213 int16_t status_;
214
215 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
216 uint16_t type_;
217
218 // Offset of start of OatClass from beginning of OatHeader. It is
219 // used to validate file position when writing.
220 uint32_t offset_;
221};
222
223// The actual oat class body contains the information about compiled methods. It is only required
224// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000225class OatWriter::OatClass {
226 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700227 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100228 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700229 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000230 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000231 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700232 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000233
234 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
235 return compiled_methods_[class_def_method_index];
236 }
237
Vladimir Marko49b0f452015-12-10 13:49:19 +0000238 // CompiledMethods for each class_def_method_index, or null if no method is available.
239 dchecked_vector<CompiledMethod*> compiled_methods_;
240
241 // Offset from OatClass::offset_ to the OatMethodOffsets for the
242 // class_def_method_index. If 0, it means the corresponding
243 // CompiledMethod entry in OatClass::compiled_methods_ should be
244 // null and that the OatClass::type_ should be kOatClassBitmap.
245 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
246
247 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248 uint32_t method_bitmap_size_;
249
250 // bit vector indexed by ClassDef method index. When
251 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
252 // method has an OatMethodOffsets in methods_offsets_, otherwise
253 // the entry was ommited to save space. If OatClassType::type_ is
254 // not is kOatClassBitmap, the bitmap will be null.
255 std::unique_ptr<BitVector> method_bitmap_;
256
257 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
258 // present in the OatClass. Note that some may be missing if
259 // OatClass::compiled_methods_ contains null values (and
260 // oat_method_offsets_offsets_from_oat_class_ should contain 0
261 // values in this case).
262 dchecked_vector<OatMethodOffsets> method_offsets_;
263 dchecked_vector<OatQuickMethodHeader> method_headers_;
264
265 private:
266 size_t GetMethodOffsetsRawSize() const {
267 return method_offsets_.size() * sizeof(method_offsets_[0]);
268 }
269
270 DISALLOW_COPY_AND_ASSIGN(OatClass);
271};
272
273class OatWriter::OatDexFile {
274 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000275 OatDexFile(const char* dex_file_location,
276 DexFileSource source,
277 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000278 OatDexFile(OatDexFile&& src) = default;
279
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000280 const char* GetLocation() const {
281 return dex_file_location_data_;
282 }
283
Vladimir Marko49b0f452015-12-10 13:49:19 +0000284 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000285 bool Write(OatWriter* oat_writer, OutputStream* out) const;
286 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
287
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100288 size_t GetClassOffsetsRawSize() const {
289 return class_offsets_.size() * sizeof(class_offsets_[0]);
290 }
291
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000292 // The source of the dex file.
293 DexFileSource source_;
294
295 // Whether to create the type lookup table.
296 CreateTypeLookupTable create_type_lookup_table_;
297
298 // Dex file size. Initialized when writing the dex file.
299 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000300
301 // Offset of start of OatDexFile from beginning of OatHeader. It is
302 // used to validate file position when writing.
303 size_t offset_;
304
305 // Data to write.
306 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000307 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000308 uint32_t dex_file_location_checksum_;
309 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000310 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000311 uint32_t lookup_table_offset_;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100312 uint32_t method_bss_mapping_offset_;
Mathieu Chartier120aa282017-08-05 16:03:03 -0700313 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000314
315 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000316 dchecked_vector<uint32_t> class_offsets_;
317
Mathieu Chartier120aa282017-08-05 16:03:03 -0700318 // Dex section layout info to serialize.
319 DexLayoutSections dex_sections_layout_;
320
Vladimir Marko49b0f452015-12-10 13:49:19 +0000321 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000322 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
323};
324
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100325#define DCHECK_OFFSET() \
326 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
327 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
328
329#define DCHECK_OFFSET_() \
330 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
331 << "file_offset=" << file_offset << " offset_=" << offset_
332
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700333OatWriter::OatWriter(bool compiling_boot_image,
334 TimingLogger* timings,
335 ProfileCompilationInfo* info,
336 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000337 : write_state_(WriteState::kAddingDexFileSources),
338 timings_(timings),
339 raw_dex_files_(),
340 zip_archives_(),
341 zipped_dex_files_(),
342 zipped_dex_file_locations_(),
343 compiler_driver_(nullptr),
344 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800345 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000346 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100347 vdex_size_(0u),
348 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100349 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100350 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100351 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000352 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000353 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100354 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000355 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100356 bss_method_entry_references_(),
357 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000358 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000359 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100360 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100361 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700362 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100363 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000364 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700365 size_dex_file_alignment_(0),
366 size_executable_offset_alignment_(0),
367 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700368 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700369 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100370 size_verifier_deps_(0),
371 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100372 size_quickening_info_(0),
373 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700374 size_interpreter_to_interpreter_bridge_(0),
375 size_interpreter_to_compiled_code_bridge_(0),
376 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800377 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700378 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700379 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700380 size_quick_to_interpreter_bridge_(0),
381 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100382 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700383 size_code_(0),
384 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100385 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100386 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700387 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700388 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700389 size_oat_dex_file_location_size_(0),
390 size_oat_dex_file_location_data_(0),
391 size_oat_dex_file_location_checksum_(0),
392 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000393 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000394 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700395 size_oat_dex_file_dex_layout_sections_offset_(0),
396 size_oat_dex_file_dex_layout_sections_(0),
397 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100398 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000399 size_oat_lookup_table_alignment_(0),
400 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000401 size_oat_class_offsets_alignment_(0),
402 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700403 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700404 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700405 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100406 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100407 size_method_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000408 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700409 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700410 profile_compilation_info_(info),
411 compact_dex_level_(compact_dex_level) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000412}
413
414bool OatWriter::AddDexFileSource(const char* filename,
415 const char* location,
416 CreateTypeLookupTable create_type_lookup_table) {
417 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
418 uint32_t magic;
419 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700420 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
421 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000422 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
423 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700424 } else if (DexFileLoader::IsMagicValid(magic)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000425 // The file is open for reading, not writing, so it's OK to let the File destructor
426 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700427 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000428 oat_dex_files_.emplace_back(location,
429 DexFileSource(raw_dex_files_.back().get()),
430 create_type_lookup_table);
431 } else if (IsZipMagic(magic)) {
432 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
433 return false;
434 }
435 } else {
436 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
437 return false;
438 }
439 return true;
440}
441
442// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700443bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 const char* location,
445 CreateTypeLookupTable create_type_lookup_table) {
446 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
447 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700448 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000449 ZipArchive* zip_archive = zip_archives_.back().get();
450 if (zip_archive == nullptr) {
451 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
452 << error_msg;
453 return false;
454 }
455 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700456 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000457 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
458 if (entry == nullptr) {
459 break;
460 }
461 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700462 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000463 const char* full_location = zipped_dex_file_locations_.back().c_str();
464 oat_dex_files_.emplace_back(full_location,
465 DexFileSource(zipped_dex_files_.back().get()),
466 create_type_lookup_table);
467 }
468 if (zipped_dex_file_locations_.empty()) {
469 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
470 return false;
471 }
472 return true;
473}
474
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000475// Add dex file source(s) from a vdex file specified by a file handle.
476bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
477 const char* location,
478 CreateTypeLookupTable create_type_lookup_table) {
479 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
480 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000481 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000482 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
483 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000484 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
485 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000486 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700487
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700488 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000489 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
490 return false;
491 }
492 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700493 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000494 const char* full_location = zipped_dex_file_locations_.back().c_str();
495 oat_dex_files_.emplace_back(full_location,
496 DexFileSource(current_dex_data),
497 create_type_lookup_table);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000498 oat_dex_files_.back().dex_file_location_checksum_ = vdex_file.GetLocationChecksum(i);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000499 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000500
501 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
502 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
503 return false;
504 }
505
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000506 if (oat_dex_files_.empty()) {
507 LOG(ERROR) << "No dex files in vdex file created from " << location;
508 return false;
509 }
510 return true;
511}
512
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000513// Add dex file source from raw memory.
514bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
515 const char* location,
516 uint32_t location_checksum,
517 CreateTypeLookupTable create_type_lookup_table) {
518 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
519 if (data.size() < sizeof(DexFile::Header)) {
520 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
521 << data.size() << " File: " << location;
522 return false;
523 }
524 if (!ValidateDexFileHeader(data.data(), location)) {
525 return false;
526 }
527 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
528 if (data.size() < header->file_size_) {
529 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
530 << " file size from header: " << header->file_size_ << " File: " << location;
531 return false;
532 }
533
534 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
535 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
536 return true;
537}
538
Calin Juravle1ce70852017-06-28 10:59:03 -0700539dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
540 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000541 locations.reserve(oat_dex_files_.size());
542 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
543 locations.push_back(oat_dex_file.GetLocation());
544 }
545 return locations;
546}
547
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700548bool OatWriter::MayHaveCompiledMethods() const {
549 return CompilerFilter::IsAnyCompilationEnabled(
550 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
551}
552
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000553bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100554 File* vdex_file,
555 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000556 InstructionSet instruction_set,
557 const InstructionSetFeatures* instruction_set_features,
558 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800559 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000560 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000561 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
562 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
563 CHECK(write_state_ == WriteState::kAddingDexFileSources);
564
David Brazdil7b49e6c2016-09-01 11:06:18 +0100565 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
566 if (!RecordOatDataOffset(oat_rodata)) {
567 return false;
568 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000569
570 std::unique_ptr<MemMap> dex_files_map;
571 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100572
573 // Initialize VDEX and OAT headers.
574 if (kIsVdexEnabled) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000575 // Reserve space for Vdex header and checksums.
576 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100577 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100578 oat_size_ = InitOatHeader(instruction_set,
579 instruction_set_features,
580 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
581 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100582
583 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
584
585 if (kIsVdexEnabled) {
Andreas Gampe8bdda5a2017-06-08 15:30:36 -0700586 std::unique_ptr<BufferedOutputStream> vdex_out =
587 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
David Brazdil7b49e6c2016-09-01 11:06:18 +0100588 // Write DEX files into VDEX, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000589 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100590 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
591 return false;
592 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100593 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000594 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100595 // Write DEX files into OAT, mmap and open them.
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000596 if (!WriteDexFiles(oat_rodata, vdex_file, update_input_vdex) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100597 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
598 return false;
599 }
600
601 // Do a bulk checksum update for Dex[]. Doing it piece by piece would be
602 // difficult because we're not using the OutputStream directly.
603 if (!oat_dex_files_.empty()) {
604 size_t size = oat_size_ - oat_dex_files_[0].dex_file_offset_;
605 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
606 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000607 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000608
Mathieu Chartier120aa282017-08-05 16:03:03 -0700609 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000610 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
611 return false;
612 }
613
Mathieu Chartier120aa282017-08-05 16:03:03 -0700614 // Write dex layout sections into the oat file.
615 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
616 return false;
617 }
618
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000619 *opened_dex_files_map = std::move(dex_files_map);
620 *opened_dex_files = std::move(dex_files);
621 write_state_ = WriteState::kPrepareLayout;
622 return true;
623}
624
Vladimir Marko74527972016-11-29 15:57:32 +0000625void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000626 CHECK(write_state_ == WriteState::kPrepareLayout);
627
Vladimir Marko944da602016-02-19 12:27:55 +0000628 relative_patcher_ = relative_patcher;
629 SetMultiOatRelativePatcherAdjustment();
630
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000631 if (compiling_boot_image_) {
632 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800633 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100634 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000635 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100636
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100637 {
638 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
639 InitBssLayout(instruction_set);
640 }
641
David Brazdil7b49e6c2016-09-01 11:06:18 +0100642 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800643 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100644 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
645 offset = InitClassOffsets(offset);
646 }
647 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000648 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800649 offset = InitOatClasses(offset);
650 }
651 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100652 TimingLogger::ScopedTiming split("InitMethodBssMappings", timings_);
653 offset = InitMethodBssMappings(offset);
654 }
655 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000656 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100657 offset = InitOatMaps(offset);
658 }
659 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100660 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
661 oat_header_->SetOatDexFilesOffset(offset);
662 offset = InitOatDexFiles(offset);
663 }
664 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000665 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800666 offset = InitOatCode(offset);
667 }
668 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000669 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800670 offset = InitOatCodeDexFiles(offset);
671 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100672 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100673 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100674
Brian Carlstrome24fa612011-09-29 00:53:55 -0700675 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800676 if (compiling_boot_image_) {
677 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000678 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800679 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000680
681 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700682}
683
Ian Rogers0571d352011-11-03 19:51:38 -0700684OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700685}
686
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687class OatWriter::DexMethodVisitor {
688 public:
689 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100690 : writer_(writer),
691 offset_(offset),
692 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700693 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100694
695 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
696 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700697 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100698 dex_file_ = dex_file;
699 class_def_index_ = class_def_index;
700 return true;
701 }
702
703 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
704
705 virtual bool EndClass() {
706 if (kIsDebugBuild) {
707 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700708 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100709 }
710 return true;
711 }
712
713 size_t GetOffset() const {
714 return offset_;
715 }
716
717 protected:
718 virtual ~DexMethodVisitor() { }
719
720 OatWriter* const writer_;
721
722 // The offset is usually advanced for each visited method by the derived class.
723 size_t offset_;
724
725 // The dex file and class def index are set in StartClass().
726 const DexFile* dex_file_;
727 size_t class_def_index_;
728};
729
730class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
731 public:
732 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100733 : DexMethodVisitor(writer, offset),
734 oat_class_index_(0u),
735 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100736
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100737 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100738 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700739 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
740 // There are no oat classes if there aren't any compiled methods.
741 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
742 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100743 method_offsets_index_ = 0u;
744 return true;
745 }
746
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100747 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100748 ++oat_class_index_;
749 return DexMethodVisitor::EndClass();
750 }
751
752 protected:
753 size_t oat_class_index_;
754 size_t method_offsets_index_;
755};
756
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100757static bool HasCompiledCode(const CompiledMethod* method) {
758 // The dextodexcompiler puts the quickening info table into the CompiledMethod
759 // for simplicity. For such methods, we will emit an OatQuickMethodHeader
760 // only when vdex is disabled.
761 return method != nullptr && (!method->GetQuickCode().empty() || !kIsVdexEnabled);
762}
763
764static bool HasQuickeningInfo(const CompiledMethod* method) {
765 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
766}
767
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100768class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
769 public:
770 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
771 : DexMethodVisitor(writer, /* offset */ 0u) {}
772
773 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
774 const ClassDataItemIterator& it) OVERRIDE {
775 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
776 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
777 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100778 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100779 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
780 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
781 MethodReference target_method = patch.TargetMethod();
782 auto refs_it = writer_->bss_method_entry_references_.find(target_method.dex_file);
783 if (refs_it == writer_->bss_method_entry_references_.end()) {
784 refs_it = writer_->bss_method_entry_references_.Put(
785 target_method.dex_file,
786 BitVector(target_method.dex_file->NumMethodIds(),
787 /* expandable */ false,
788 Allocator::GetMallocAllocator()));
789 refs_it->second.ClearAllBits();
790 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700791 refs_it->second.SetBit(target_method.index);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100792 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
793 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
794 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
795 writer_->bss_type_entries_.Overwrite(ref, /* placeholder */ 0u);
796 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
797 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
798 writer_->bss_string_entries_.Overwrite(ref, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100799 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
800 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100801 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100802 }
803 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100804 } else {
805 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100806 }
807 return true;
808 }
809};
810
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100811class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
812 public:
813 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100814 : DexMethodVisitor(writer, offset),
815 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100816 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000817 size_t num_classes = 0u;
818 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
819 num_classes += oat_dex_file.class_offsets_.size();
820 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700821 // If we aren't compiling only reserve headers.
822 writer_->oat_class_headers_.reserve(num_classes);
823 if (writer->MayHaveCompiledMethods()) {
824 writer->oat_classes_.reserve(num_classes);
825 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100826 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100827 // If there are any classes, the class offsets allocation aligns the offset.
828 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100829 }
830
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100831 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832 DexMethodVisitor::StartClass(dex_file, class_def_index);
833 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100834 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100835 return true;
836 }
837
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300838 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100839 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100840 // Fill in the compiled_methods_ array for methods that have a
841 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100842 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100843 // OatMethodOffsets for the compiled methods.
844 uint32_t method_idx = it.GetMemberIndex();
845 CompiledMethod* compiled_method =
846 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
847 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100848 if (HasCompiledCode(compiled_method)) {
849 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100850 }
851 return true;
852 }
853
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100854 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100855 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100856 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700857 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
858 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700859 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
860 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700861 // The oat class status is used only for verification of resolved classes,
862 // so use kStatusErrorResolved whether the class was resolved or unresolved
863 // during compile-time verification.
864 status = mirror::Class::kStatusErrorResolved;
865 } else {
866 status = mirror::Class::kStatusNotReady;
867 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100868 }
869
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700870 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100871 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700872 compiled_methods_.size(),
873 status);
874 OatClassHeader& header = writer_->oat_class_headers_.back();
875 offset_ += header.SizeOf();
876 if (writer_->MayHaveCompiledMethods()) {
877 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100878 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700879 header.type_);
880 offset_ += writer_->oat_classes_.back().SizeOf();
881 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100882 return DexMethodVisitor::EndClass();
883 }
884
885 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000886 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100887 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100888};
889
Igor Murashkin545412b2017-08-17 15:26:54 -0700890// CompiledMethod + metadata required to do ordered method layout.
891//
892// See also OrderedMethodVisitor.
893struct OatWriter::OrderedMethodData {
894 ProfileCompilationInfo::MethodHotness method_hotness;
895 OatClass* oat_class;
896 CompiledMethod* compiled_method;
897 MethodReference method_reference;
898 size_t method_offsets_index;
899
900 size_t class_def_index;
901 uint32_t access_flags;
902 const DexFile::CodeItem* code_item;
903
904 // A value of -1 denotes missing debug info
905 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
906 // Index into writer_->method_info_
907 size_t debug_info_idx;
908
909 bool HasDebugInfo() const {
910 return debug_info_idx != kDebugInfoIdxInvalid;
911 }
912
913 // Bin each method according to the profile flags.
914 //
915 // Groups by e.g.
916 // -- not hot at all
917 // -- hot
918 // -- hot and startup
919 // -- hot and post-startup
920 // -- hot and startup and poststartup
921 // -- startup
922 // -- startup and post-startup
923 // -- post-startup
924 //
925 // (See MethodHotness enum definition for up-to-date binning order.)
926 bool operator<(const OrderedMethodData& other) const {
927 if (kOatWriterForceOatCodeLayout) {
928 // Development flag: Override default behavior by sorting by name.
929
930 std::string name = method_reference.PrettyMethod();
931 std::string other_name = other.method_reference.PrettyMethod();
932 return name < other_name;
933 }
934
935 // Use the profile's method hotness to determine sort order.
936 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
937 return true;
938 }
939
940 // Default: retain the original order.
941 return false;
942 }
943
944 private:
945 // Used to determine relative order for OAT code layout when determining
946 // binning.
947 size_t GetMethodHotnessOrder() const {
948 bool hotness[] = {
949 method_hotness.IsHot(),
950 method_hotness.IsStartup(),
951 method_hotness.IsPostStartup()
952 };
953
954
955 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
956 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
957 // time that memory is referenced in the process.
958
959 size_t hotness_bits = 0;
960 for (size_t i = 0; i < arraysize(hotness); ++i) {
961 if (hotness[i]) {
962 hotness_bits |= (1 << i);
963 }
964 }
965
966 if (kIsDebugBuild) {
967 // Check for bins that are always-empty given a real profile.
968 if (method_hotness.IsHot() &&
969 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
970 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -0700971 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
972 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -0700973 // This is not fatal, so only warn.
974 }
975 }
976
977 return hotness_bits;
978 }
979};
980
981// Given a queue of CompiledMethod in some total order,
982// visit each one in that order.
983class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100984 public:
Igor Murashkin545412b2017-08-17 15:26:54 -0700985 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
986 : ordered_methods_(std::move(ordered_methods)) {
987 }
988
989 virtual ~OrderedMethodVisitor() {}
990
991 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
992 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
993 if (!VisitStart()) {
994 return false;
995 }
996
997 for (const OrderedMethodData& method_data : ordered_methods_) {
998 if (!VisitMethod(method_data)) {
999 return false;
1000 }
1001 }
1002
1003 return VisitComplete();
1004 }
1005
1006 // Invoked once at the beginning, prior to visiting anything else.
1007 //
1008 // Return false to abort further visiting.
1009 virtual bool VisitStart() { return true; }
1010
1011 // Invoked repeatedly in the order specified by `ordered_methods`.
1012 //
1013 // Return false to short-circuit and to stop visiting further methods.
1014 virtual bool VisitMethod(const OrderedMethodData& method_data)
1015 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1016
1017 // Invoked once at the end, after every other method has been successfully visited.
1018 //
1019 // Return false to indicate the overall `Visit` has failed.
1020 virtual bool VisitComplete() = 0;
1021
1022 OrderedMethodList ReleaseOrderedMethods() {
1023 return std::move(ordered_methods_);
1024 }
1025
1026 private:
1027 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1028 // Methods can be inserted more than once in case of duplicated methods.
1029 OrderedMethodList ordered_methods_;
1030};
1031
1032// Visit every compiled method in order to determine its order within the OAT file.
1033// Methods from the same class do not need to be adjacent in the OAT code.
1034class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1035 public:
1036 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1037 : OatDexMethodVisitor(writer, offset) {
1038 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001039
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001040 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001041 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001042 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001043 }
1044
Igor Murashkin545412b2017-08-17 15:26:54 -07001045 bool VisitMethod(size_t class_def_method_index,
1046 const ClassDataItemIterator& it)
1047 OVERRIDE
1048 REQUIRES_SHARED(Locks::mutator_lock_) {
1049 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1050
Vladimir Marko49b0f452015-12-10 13:49:19 +00001051 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001052 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1053
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001054 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001055 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001056
Igor Murashkin545412b2017-08-17 15:26:54 -07001057 {
1058 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1059 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1060 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001061
Igor Murashkin545412b2017-08-17 15:26:54 -07001062 // Debug method info must be pushed in the original order
1063 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1064 // ElfCompilationUnitWriter::Write requires this.
1065 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1066 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1067 writer_->method_info_.push_back(info);
1068
1069 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1070 // once we know the offsets.
1071 //
1072 // Store the index into writer_->method_info_ since future push-backs
1073 // could reallocate and change the underlying data address.
1074 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001076 }
1077
1078 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1079
1080 // Lookup method hotness from profile, if available.
1081 // Otherwise assume a default of none-hotness.
1082 ProfileCompilationInfo::MethodHotness method_hotness =
1083 writer_->profile_compilation_info_ != nullptr
1084 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1085 : ProfileCompilationInfo::MethodHotness();
1086
1087 // Handle duplicate methods by pushing them repeatedly.
1088 OrderedMethodData method_data = {
1089 method_hotness,
1090 oat_class,
1091 compiled_method,
1092 method_ref,
1093 method_offsets_index_,
1094 class_def_index_,
1095 it.GetMethodAccessFlags(),
1096 it.GetMethodCodeItem(),
1097 debug_info_idx
1098 };
1099 ordered_methods_.push_back(method_data);
1100
1101 method_offsets_index_++;
1102 }
1103
1104 return true;
1105 }
1106
1107 OrderedMethodList ReleaseOrderedMethods() {
1108 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1109 // Sort by the method ordering criteria (in OrderedMethodData).
1110 // Since most methods will have the same ordering criteria,
1111 // we preserve the original insertion order within the same sort order.
1112 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1113 } else {
1114 // The profile-less behavior is as if every method had 0 hotness
1115 // associated with it.
1116 //
1117 // Since sorting all methods with hotness=0 should give back the same
1118 // order as before, don't do anything.
1119 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1120 }
1121
1122 return std::move(ordered_methods_);
1123 }
1124
1125 private:
1126 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1127 // Methods can be inserted more than once in case of duplicated methods.
1128 OrderedMethodList ordered_methods_;
1129};
1130
1131// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1132class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1133 public:
1134 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1135 size_t offset,
1136 OrderedMethodList ordered_methods)
1137 : LayoutReserveOffsetCodeMethodVisitor(writer,
1138 offset,
1139 writer->GetCompilerDriver()->GetCompilerOptions(),
1140 std::move(ordered_methods)) {
1141 }
1142
1143 virtual bool VisitComplete() OVERRIDE {
1144 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1145 if (generate_debug_info_) {
1146 std::vector<debug::MethodDebugInfo> thunk_infos =
1147 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1148 writer_->method_info_.insert(writer_->method_info_.end(),
1149 std::make_move_iterator(thunk_infos.begin()),
1150 std::make_move_iterator(thunk_infos.end()));
1151 }
1152 return true;
1153 }
1154
1155 virtual bool VisitMethod(const OrderedMethodData& method_data)
1156 OVERRIDE
1157 REQUIRES_SHARED(Locks::mutator_lock_) {
1158 OatClass* oat_class = method_data.oat_class;
1159 CompiledMethod* compiled_method = method_data.compiled_method;
1160 const MethodReference& method_ref = method_data.method_reference;
1161 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1162 size_t class_def_index = method_data.class_def_index;
1163 uint32_t access_flags = method_data.access_flags;
1164 const DexFile::CodeItem* code_item = method_data.code_item;
1165 bool has_debug_info = method_data.HasDebugInfo();
1166 size_t debug_info_idx = method_data.debug_info_idx;
1167
1168 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1169
1170 // Derived from CompiledMethod.
1171 uint32_t quick_code_offset = 0;
1172
1173 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1174 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1175 uint32_t thumb_offset = compiled_method->CodeDelta();
1176
1177 // Deduplicate code arrays if we are not producing debuggable code.
1178 bool deduped = true;
1179 if (debuggable_) {
1180 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1181 if (quick_code_offset != 0u) {
1182 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1183 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001184 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001185 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1186 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001187 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001188 } else {
1189 quick_code_offset = dedupe_map_.GetOrCreate(
1190 compiled_method,
1191 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1192 deduped = false;
1193 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1194 });
1195 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001196
Igor Murashkin545412b2017-08-17 15:26:54 -07001197 if (code_size != 0) {
1198 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1199 // TODO: Should this be a hard failure?
1200 LOG(WARNING) << "Multiple definitions of "
1201 << method_ref.dex_file->PrettyMethod(method_ref.index)
1202 << " offsets " << relative_patcher_->GetOffset(method_ref)
1203 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001204 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001205 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1206 }
1207 }
1208
1209 // Update quick method header.
1210 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1211 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1212 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1213 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1214 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1215 // to 0-offset and we need to adjust it by code_offset.
1216 uint32_t code_offset = quick_code_offset - thumb_offset;
1217 if (!compiled_method->GetQuickCode().empty()) {
1218 // If the code is compiled, we write the offset of the stack map relative
1219 // to the code,
1220 if (vmap_table_offset != 0u) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001221 vmap_table_offset += code_offset;
1222 DCHECK_LT(vmap_table_offset, code_offset);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001223 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001224 if (method_info_offset != 0u) {
1225 method_info_offset += code_offset;
1226 DCHECK_LT(method_info_offset, code_offset);
1227 }
1228 } else {
1229 CHECK(!kIsVdexEnabled);
1230 // We write the offset of the quickening info relative to the code.
1231 vmap_table_offset += code_offset;
1232 DCHECK_LT(vmap_table_offset, code_offset);
1233 }
1234 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1235 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1236 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1237 *method_header = OatQuickMethodHeader(vmap_table_offset,
1238 method_info_offset,
1239 frame_size_in_bytes,
1240 core_spill_mask,
1241 fp_spill_mask,
1242 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001243
Igor Murashkin545412b2017-08-17 15:26:54 -07001244 if (!deduped) {
1245 // Update offsets. (Checksum is updated when writing.)
1246 offset_ += sizeof(*method_header); // Method header is prepended before code.
1247 offset_ += code_size;
1248 // Record absolute patch locations.
1249 if (!compiled_method->GetPatches().empty()) {
1250 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1251 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1252 if (!patch.IsPcRelative()) {
1253 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001254 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001255 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001256 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001257 }
1258
Igor Murashkin545412b2017-08-17 15:26:54 -07001259 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1260 if (generate_debug_info_ && code_size != 0) {
1261 DCHECK(has_debug_info);
1262
1263 bool has_code_info = method_header->IsOptimized();
1264 // Record debug information for this function if we are doing that.
1265 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1266 DCHECK(info.trampoline_name.empty());
1267 info.dex_file = method_ref.dex_file;
1268 info.class_def_index = class_def_index;
1269 info.dex_method_index = method_ref.index;
1270 info.access_flags = access_flags;
1271 info.code_item = code_item;
1272 info.isa = compiled_method->GetInstructionSet();
1273 info.deduped = deduped;
1274 info.is_native_debuggable = native_debuggable_;
1275 info.is_optimized = method_header->IsOptimized();
1276 info.is_code_address_text_relative = true;
1277 info.code_address = code_offset - executable_offset_;
1278 info.code_size = code_size;
1279 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1280 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1281 info.cfi = compiled_method->GetCFIInfo();
1282 } else {
1283 DCHECK(!has_debug_info);
1284 }
1285
1286 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1287 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1288 offsets->code_offset_ = quick_code_offset;
1289
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001290 return true;
1291 }
1292
Igor Murashkin545412b2017-08-17 15:26:54 -07001293 size_t GetOffset() const {
1294 return offset_;
1295 }
1296
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001298 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1299 size_t offset,
1300 const CompilerOptions& compiler_options,
1301 OrderedMethodList ordered_methods)
1302 : OrderedMethodVisitor(std::move(ordered_methods)),
1303 writer_(writer),
1304 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001305 relative_patcher_(writer->relative_patcher_),
1306 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1307 debuggable_(compiler_options.GetDebuggable()),
1308 native_debuggable_(compiler_options.GetNativeDebuggable()),
1309 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1310 writer->absolute_patch_locations_.reserve(
1311 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1312 }
1313
Vladimir Marko20f85592015-03-19 10:07:02 +00001314 struct CodeOffsetsKeyComparator {
1315 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001316 // Code is deduplicated by CompilerDriver, compare only data pointers.
1317 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1318 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001319 }
1320 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001321 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1322 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001323 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001324 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1325 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1326 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001327 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1328 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001329 }
1330 return false;
1331 }
1332 };
1333
David Srbecky009e2a62015-04-15 02:46:30 +01001334 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001335 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001336 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001337 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001338 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1339 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001340 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1341 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1342 }
1343
Igor Murashkin545412b2017-08-17 15:26:54 -07001344 OatWriter* writer_;
1345
1346 // Offset of the code of the compiled methods.
1347 size_t offset_;
1348
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001349 // Deduplication is already done on a pointer basis by the compiler driver,
1350 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001351 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001352
Vladimir Marko1b404a82017-09-01 13:35:26 +01001353 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001354 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001355 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001356 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001357 const bool native_debuggable_;
1358 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001359};
1360
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001361class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1362 public:
1363 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001364 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001365
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001366 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001367 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001368 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001369 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1370
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001371 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001372 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001373 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001374
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001375 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1376 uint32_t map_size = map.size() * sizeof(map[0]);
1377 if (map_size != 0u) {
1378 size_t offset = dedupe_map_.GetOrCreate(
1379 map.data(),
1380 [this, map_size]() {
1381 uint32_t new_offset = offset_;
1382 offset_ += map_size;
1383 return new_offset;
1384 });
1385 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1386 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1387 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001388 }
1389 ++method_offsets_index_;
1390 }
1391
1392 return true;
1393 }
1394
1395 private:
1396 // Deduplication is already done on a pointer basis by the compiler driver,
1397 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001398 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001399};
1400
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001401class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1402 public:
1403 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1404
1405 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001406 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001407 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1408 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1409
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001410 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001411 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1412 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1413 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1414 const uint32_t map_size = map.size() * sizeof(map[0]);
1415 if (map_size != 0u) {
1416 size_t offset = dedupe_map_.GetOrCreate(
1417 map.data(),
1418 [this, map_size]() {
1419 uint32_t new_offset = offset_;
1420 offset_ += map_size;
1421 return new_offset;
1422 });
1423 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1424 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1425 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1426 }
1427 ++method_offsets_index_;
1428 }
1429
1430 return true;
1431 }
1432
1433 private:
1434 // Deduplication is already done on a pointer basis by the compiler driver,
1435 // so we can simply compare the pointers to find out if things are duplicated.
1436 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1437};
1438
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001439class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1440 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001441 InitImageMethodVisitor(OatWriter* writer,
1442 size_t offset,
1443 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001444 : OatDexMethodVisitor(writer, offset),
1445 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001446 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001447 dex_files_(dex_files),
1448 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001449
1450 // Handle copied methods here. Copy pointer to quick code from
1451 // an origin method to a copied method only if they are
1452 // in the same oat file. If the origin and the copied methods are
1453 // in different oat files don't touch the copied method.
1454 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001455 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001456 REQUIRES_SHARED(Locks::mutator_lock_) {
1457 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1458 // Skip classes that are not in the image.
1459 if (!IsImageClass()) {
1460 return true;
1461 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001462 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001463 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1464 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1465 if (klass != nullptr) {
1466 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1467 // Find origin method. Declaring class and dex_method_idx
1468 // in the copied method should be the same as in the origin
1469 // method.
1470 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001471 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001472 declaring_class->GetDexCache(),
1473 method.GetDexMethodIndex(),
1474 pointer_size_);
1475 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001476 CHECK(!origin->IsDirect());
1477 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001478 if (IsInOatFile(&declaring_class->GetDexFile())) {
1479 const void* code_ptr =
1480 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1481 if (code_ptr == nullptr) {
1482 methods_to_process_.push_back(std::make_pair(&method, origin));
1483 } else {
1484 method.SetEntryPointFromQuickCompiledCodePtrSize(
1485 code_ptr, pointer_size_);
1486 }
1487 }
1488 }
1489 }
1490 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001491 }
1492
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001493 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001494 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001495 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001496 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001497 return true;
1498 }
1499
Vladimir Marko49b0f452015-12-10 13:49:19 +00001500 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001501 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1502
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001503 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001504 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001505 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1506 offsets = oat_class->method_offsets_[method_offsets_index_];
1507 ++method_offsets_index_;
1508 }
1509
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001510 Thread* self = Thread::Current();
1511 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001512 ArtMethod* method;
1513 if (writer_->HasBootImage()) {
1514 const InvokeType invoke_type = it.GetMethodInvokeType(
1515 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001516 // Unchecked as we hold mutator_lock_ on entry.
1517 ScopedObjectAccessUnchecked soa(self);
1518 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001519 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001520 *dex_file_,
1521 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001522 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001523 ScopedNullHandle<mirror::ClassLoader>(),
1524 nullptr,
1525 invoke_type);
1526 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001527 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001528 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001529 self->AssertPendingException();
1530 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001531 std::string dump = exc->Dump();
1532 LOG(FATAL) << dump;
1533 UNREACHABLE();
1534 }
1535 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001536 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001537 // 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 +01001538 // entrypoint. This is not fatal since we shall use a resolution method.
1539 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001540 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001541 if (method != nullptr &&
1542 compiled_method != nullptr &&
1543 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001544 method->SetEntryPointFromQuickCompiledCodePtrSize(
1545 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1546 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001547
1548 return true;
1549 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001550
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001551 // Check whether current class is image class
1552 bool IsImageClass() {
1553 const DexFile::TypeId& type_id =
1554 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1555 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1556 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1557 }
1558
1559 // Check whether specified dex file is in the compiled oat file.
1560 bool IsInOatFile(const DexFile* dex_file) {
1561 return ContainsElement(*dex_files_, dex_file);
1562 }
1563
1564 // Assign a pointer to quick code for copied methods
1565 // not handled in the method StartClass
1566 void Postprocess() {
1567 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1568 ArtMethod* method = p.first;
1569 ArtMethod* origin = p.second;
1570 const void* code_ptr =
1571 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1572 if (code_ptr != nullptr) {
1573 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1574 }
1575 }
1576 }
1577
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001578 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001579 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001580 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001581 const std::vector<const DexFile*>* dex_files_;
1582 ClassLinker* const class_linker_;
1583 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001584};
1585
Igor Murashkin545412b2017-08-17 15:26:54 -07001586class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001587 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001588 WriteCodeMethodVisitor(OatWriter* writer,
1589 OutputStream* out,
1590 const size_t file_offset,
1591 size_t relative_offset,
1592 OrderedMethodList ordered_methods)
1593 : OrderedMethodVisitor(std::move(ordered_methods)),
1594 writer_(writer),
1595 offset_(relative_offset),
1596 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001597 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1598 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1599 out_(out),
1600 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001601 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001602 dex_cache_(nullptr),
1603 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001604 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001605 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001606 // If we're creating the image, the address space must be ready so that we can apply patches.
1607 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001608 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001609 }
1610
Igor Murashkin545412b2017-08-17 15:26:54 -07001611 virtual bool VisitStart() OVERRIDE {
1612 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001613 }
1614
Igor Murashkin545412b2017-08-17 15:26:54 -07001615 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001616 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001617 dex_file_ = dex_file;
1618
1619 // Ordered method visiting is only for compiled methods.
1620 DCHECK(writer_->MayHaveCompiledMethods());
1621
Mathieu Chartier72041a02017-07-14 18:23:25 -07001622 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1623 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1624 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1625 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1626 DCHECK(dex_cache_ != nullptr);
1627 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001628 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001629 }
1630
1631 virtual bool VisitComplete() {
1632 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1633 if (UNLIKELY(offset_ == 0u)) {
1634 PLOG(ERROR) << "Failed to write final relative call thunks";
1635 return false;
1636 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001637 return true;
1638 }
1639
Igor Murashkin545412b2017-08-17 15:26:54 -07001640 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001641 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001642 const MethodReference& method_ref = method_data.method_reference;
1643 UpdateDexFileAndDexCache(method_ref.dex_file);
1644
1645 OatClass* oat_class = method_data.oat_class;
1646 CompiledMethod* compiled_method = method_data.compiled_method;
1647 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001648
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001649 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001650 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001651 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001652
Igor Murashkin545412b2017-08-17 15:26:54 -07001653 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1654 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1655 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001656
Igor Murashkin545412b2017-08-17 15:26:54 -07001657 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1658 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1659
1660 // Deduplicate code arrays.
1661 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1662 if (method_offsets.code_offset_ > offset_) {
1663 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1664 if (offset_ == 0u) {
1665 ReportWriteFailure("relative call thunk", method_ref);
1666 return false;
1667 }
1668 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1669 if (alignment_size != 0) {
1670 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1671 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001672 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001673 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001674 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001675 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001676 }
1677 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1678 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1679 DCHECK_EQ(method_offsets.code_offset_,
1680 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1681 << dex_file_->PrettyMethod(method_ref.index);
1682 const OatQuickMethodHeader& method_header =
1683 oat_class->method_headers_[method_offsets_index];
1684 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1685 ReportWriteFailure("method header", method_ref);
1686 return false;
1687 }
1688 writer_->size_method_header_ += sizeof(method_header);
1689 offset_ += sizeof(method_header);
1690 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001691
Igor Murashkin545412b2017-08-17 15:26:54 -07001692 if (!compiled_method->GetPatches().empty()) {
1693 patched_code_.assign(quick_code.begin(), quick_code.end());
1694 quick_code = ArrayRef<const uint8_t>(patched_code_);
1695 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1696 uint32_t literal_offset = patch.LiteralOffset();
1697 switch (patch.GetType()) {
1698 case LinkerPatch::Type::kMethodBssEntry: {
1699 uint32_t target_offset =
1700 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1701 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1702 patch,
1703 offset_ + literal_offset,
1704 target_offset);
1705 break;
1706 }
1707 case LinkerPatch::Type::kCallRelative: {
1708 // NOTE: Relative calls across oat files are not supported.
1709 uint32_t target_offset = GetTargetOffset(patch);
1710 writer_->relative_patcher_->PatchCall(&patched_code_,
1711 literal_offset,
1712 offset_ + literal_offset,
1713 target_offset);
1714 break;
1715 }
1716 case LinkerPatch::Type::kStringRelative: {
1717 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1718 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1719 patch,
1720 offset_ + literal_offset,
1721 target_offset);
1722 break;
1723 }
1724 case LinkerPatch::Type::kStringInternTable: {
1725 uint32_t target_offset = GetInternTableEntryOffset(patch);
1726 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1727 patch,
1728 offset_ + literal_offset,
1729 target_offset);
1730 break;
1731 }
1732 case LinkerPatch::Type::kStringBssEntry: {
1733 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1734 uint32_t target_offset =
1735 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1736 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1737 patch,
1738 offset_ + literal_offset,
1739 target_offset);
1740 break;
1741 }
1742 case LinkerPatch::Type::kTypeRelative: {
1743 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1744 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1745 patch,
1746 offset_ + literal_offset,
1747 target_offset);
1748 break;
1749 }
1750 case LinkerPatch::Type::kTypeClassTable: {
1751 uint32_t target_offset = GetClassTableEntryOffset(patch);
1752 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1753 patch,
1754 offset_ + literal_offset,
1755 target_offset);
1756 break;
1757 }
1758 case LinkerPatch::Type::kTypeBssEntry: {
1759 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1760 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1761 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1762 patch,
1763 offset_ + literal_offset,
1764 target_offset);
1765 break;
1766 }
1767 case LinkerPatch::Type::kCall: {
1768 uint32_t target_offset = GetTargetOffset(patch);
1769 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1770 break;
1771 }
1772 case LinkerPatch::Type::kMethodRelative: {
1773 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1774 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1775 patch,
1776 offset_ + literal_offset,
1777 target_offset);
1778 break;
1779 }
1780 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1781 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1782 patch,
1783 offset_ + literal_offset);
1784 break;
1785 }
1786 default: {
1787 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1788 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001789 }
1790 }
1791 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001792 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001793
1794 if (!out->WriteFully(quick_code.data(), code_size)) {
1795 ReportWriteFailure("method code", method_ref);
1796 return false;
1797 }
1798 writer_->size_code_ += code_size;
1799 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001800 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001801 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001802
1803 return true;
1804 }
1805
Igor Murashkin545412b2017-08-17 15:26:54 -07001806 size_t GetOffset() const {
1807 return offset_;
1808 }
1809
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001810 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001811 OatWriter* const writer_;
1812
1813 // Updated in VisitMethod as methods are written out.
1814 size_t offset_;
1815
1816 // Potentially varies with every different VisitMethod.
1817 // Used to determine which DexCache to use when finding ArtMethods.
1818 const DexFile* dex_file_;
1819
1820 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001821 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001822 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001823 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001824 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001825 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001826 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001827 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001828 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001829 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001830 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001831
Igor Murashkin545412b2017-08-17 15:26:54 -07001832 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001833 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001834 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001835 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001836
Mathieu Chartiere401d142015-04-22 13:56:20 -07001837 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001838 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001839 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001840 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001841 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1842 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001843 ArtMethod* method =
1844 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001845 CHECK(method != nullptr);
1846 return method;
1847 }
1848
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001849 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001850 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1851 // If there's no new compiled code, either we're compiling an app and the target method
1852 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001853 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001854 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001855 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001856 const void* oat_code_offset =
1857 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001858 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001859 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001860 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1861 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1862 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1863 target_offset = PointerToLowMemUInt32(oat_code_offset);
1864 } else {
1865 target_offset = target->IsNative()
1866 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1867 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1868 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001869 }
1870 return target_offset;
1871 }
1872
Vladimir Markocd556b02017-02-03 11:47:34 +00001873 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001874 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001875 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001876 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001877 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1878 }
1879
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001880 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001881 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001882 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001883 ObjPtr<mirror::Class> type =
1884 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001885 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001886 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001887 }
1888
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001889 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001890 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001891 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1892 patch.TargetStringIndex(),
Vladimir Markof25cc732017-03-16 16:18:15 +00001893 GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001894 DCHECK(string != nullptr);
1895 DCHECK(writer_->HasBootImage() ||
1896 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1897 return string;
1898 }
1899
Vladimir Marko65979462017-05-19 17:25:12 +01001900 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1901 DCHECK(writer_->HasBootImage());
1902 method = writer_->image_writer_->GetImageMethodAddress(method);
1903 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1904 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1905 // TODO: Clean up offset types. The target offset must be treated as signed.
1906 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1907 }
1908
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001909 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001910 DCHECK(writer_->HasBootImage());
1911 object = writer_->image_writer_->GetImageAddress(object);
1912 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1913 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1914 // TODO: Clean up offset types. The target offset must be treated as signed.
1915 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1916 }
1917
Vladimir Markof4da6752014-08-01 19:04:18 +01001918 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001919 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001920 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001921 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001922 } else {
1923 // NOTE: We're using linker patches for app->boot references when the image can
1924 // be relocated and therefore we need to emit .oat_patches. We're not using this
1925 // for app->app references, so check that the object is in the image space.
1926 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001927 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001928 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001929 uint32_t address = PointerToLowMemUInt32(object);
1930 DCHECK_LE(offset + 4, code->size());
1931 uint8_t* data = &(*code)[offset];
1932 data[0] = address & 0xffu;
1933 data[1] = (address >> 8) & 0xffu;
1934 data[2] = (address >> 16) & 0xffu;
1935 data[3] = (address >> 24) & 0xffu;
1936 }
1937
1938 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001939 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001940 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001941 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001942 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1943 // TODO: Clean up offset types.
1944 // The target_offset must be treated as signed for cross-oat patching.
1945 const void* target = reinterpret_cast<const void*>(
1946 writer_->image_writer_->GetOatDataBegin(oat_index) +
1947 static_cast<int32_t>(target_offset));
1948 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001949 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001950 DCHECK_LE(offset + 4, code->size());
1951 uint8_t* data = &(*code)[offset];
1952 data[0] = address & 0xffu;
1953 data[1] = (address >> 8) & 0xffu;
1954 data[2] = (address >> 16) & 0xffu;
1955 data[3] = (address >> 24) & 0xffu;
1956 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001957
1958 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
1959 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
1960 REQUIRES_SHARED(Locks::mutator_lock_) {
1961 DCHECK(!writer_->HasBootImage());
1962 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
1963 *patch.TargetStringDexFile(), patch.TargetStringIndex());
1964 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01001965 return GetBootImageTableEntryOffset(string_root);
1966 }
1967
1968 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
1969 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
1970 REQUIRES_SHARED(Locks::mutator_lock_) {
1971 DCHECK(!writer_->HasBootImage());
1972 const uint8_t* table_slot =
1973 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1974 DCHECK(table_slot != nullptr);
1975 return GetBootImageTableEntryOffset(table_slot);
1976 }
1977
1978 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001979 uint32_t base_offset = writer_->bss_start_;
1980 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1981 const uint8_t* const_tables_begin =
1982 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01001983 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001984 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
1985 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
1986 return base_offset + offset;
1987 }
1988 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
1989 }
1990 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
1991 UNREACHABLE();
1992 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001993};
1994
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001995class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1996 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001997 WriteMapMethodVisitor(OatWriter* writer,
1998 OutputStream* out,
1999 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002000 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002001 : OatDexMethodVisitor(writer, relative_offset),
2002 out_(out),
2003 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002004
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002005 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002006 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002007 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2008
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002009 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002010 size_t file_offset = file_offset_;
2011 OutputStream* out = out_;
2012
Mingyao Yang063fc772016-08-02 11:02:54 -07002013 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002014 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002015 ++method_offsets_index_;
2016
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002017 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2018 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2019 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002020 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002021
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002022 // If vdex is enabled, only emit the map for compiled code. The quickening info
2023 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002024 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002025 // Transform map_offset to actual oat data offset.
2026 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2027 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002028 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002029
2030 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2031 size_t map_size = map.size() * sizeof(map[0]);
2032 if (map_offset == offset_) {
2033 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002034 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002035 ReportWriteFailure(it);
2036 return false;
2037 }
2038 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002039 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002040 }
2041 DCHECK_OFFSET_();
2042 }
2043
2044 return true;
2045 }
2046
2047 private:
2048 OutputStream* const out_;
2049 size_t const file_offset_;
2050
2051 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002052 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002053 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002054 }
2055};
2056
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002057class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2058 public:
2059 WriteMethodInfoVisitor(OatWriter* writer,
2060 OutputStream* out,
2061 const size_t file_offset,
2062 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002063 : OatDexMethodVisitor(writer, relative_offset),
2064 out_(out),
2065 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002066
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002067 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002068 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2069 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2070
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002071 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002072 size_t file_offset = file_offset_;
2073 OutputStream* out = out_;
2074 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2075 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2076 ++method_offsets_index_;
2077 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2078 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2079 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2080 << dex_file_->PrettyMethod(it.GetMemberIndex());
2081 if (map_offset != 0u) {
2082 // Transform map_offset to actual oat data offset.
2083 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2084 DCHECK_NE(map_offset, 0u);
2085 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2086
2087 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2088 size_t map_size = map.size() * sizeof(map[0]);
2089 if (map_offset == offset_) {
2090 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2091 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2092 ReportWriteFailure(it);
2093 return false;
2094 }
2095 offset_ += map_size;
2096 }
2097 }
2098 DCHECK_OFFSET_();
2099 }
2100
2101 return true;
2102 }
2103
2104 private:
2105 OutputStream* const out_;
2106 size_t const file_offset_;
2107
2108 void ReportWriteFailure(const ClassDataItemIterator& it) {
2109 PLOG(ERROR) << "Failed to write map for "
2110 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2111 }
2112};
2113
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002114// Visit all methods from all classes in all dex files with the specified visitor.
2115bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2116 for (const DexFile* dex_file : *dex_files_) {
2117 const size_t class_def_count = dex_file->NumClassDefs();
2118 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2119 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2120 return false;
2121 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002122 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002123 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2124 const uint8_t* class_data = dex_file->GetClassData(class_def);
2125 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2126 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002127 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002128 size_t class_def_method_index = 0u;
2129 while (it.HasNextDirectMethod()) {
2130 if (!visitor->VisitMethod(class_def_method_index, it)) {
2131 return false;
2132 }
2133 ++class_def_method_index;
2134 it.Next();
2135 }
2136 while (it.HasNextVirtualMethod()) {
2137 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
2138 return false;
2139 }
2140 ++class_def_method_index;
2141 it.Next();
2142 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002143 }
2144 }
2145 if (UNLIKELY(!visitor->EndClass())) {
2146 return false;
2147 }
2148 }
2149 }
2150 return true;
2151}
2152
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002153size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2154 const InstructionSetFeatures* instruction_set_features,
2155 uint32_t num_dex_files,
2156 SafeMap<std::string, std::string>* key_value_store) {
2157 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2158 oat_header_.reset(OatHeader::Create(instruction_set,
2159 instruction_set_features,
2160 num_dex_files,
2161 key_value_store));
2162 size_oat_header_ += sizeof(OatHeader);
2163 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002164 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002165}
2166
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002167size_t OatWriter::InitClassOffsets(size_t offset) {
2168 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002169 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002170 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2171 if (!oat_dex_file.class_offsets_.empty()) {
2172 // Class offsets are required to be 4 byte aligned.
2173 offset = RoundUp(offset, 4u);
2174 oat_dex_file.class_offsets_offset_ = offset;
2175 offset += oat_dex_file.GetClassOffsetsRawSize();
2176 DCHECK_ALIGNED(offset, 4u);
2177 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002178 }
2179 return offset;
2180}
2181
Brian Carlstrom389efb02012-01-11 12:06:26 -08002182size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002183 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002184 InitOatClassesMethodVisitor visitor(this, offset);
2185 bool success = VisitDexMethods(&visitor);
2186 CHECK(success);
2187 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002188
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002189 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002190 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002191 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2192 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002193 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002194 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002195 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002196 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002197 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002198 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002199
2200 return offset;
2201}
2202
2203size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002204 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002205 return offset;
2206 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002207 {
2208 InitMapMethodVisitor visitor(this, offset);
2209 bool success = VisitDexMethods(&visitor);
2210 DCHECK(success);
2211 offset = visitor.GetOffset();
2212 }
2213 {
2214 InitMethodInfoVisitor visitor(this, offset);
2215 bool success = VisitDexMethods(&visitor);
2216 DCHECK(success);
2217 offset = visitor.GetOffset();
2218 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002219 return offset;
2220}
2221
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002222size_t OatWriter::InitMethodBssMappings(size_t offset) {
2223 size_t number_of_dex_files = 0u;
2224 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2225 const DexFile* dex_file = (*dex_files_)[i];
2226 auto it = bss_method_entry_references_.find(dex_file);
2227 if (it != bss_method_entry_references_.end()) {
2228 const BitVector& method_indexes = it->second;
2229 ++number_of_dex_files;
2230 // If there are any classes, the class offsets allocation aligns the offset
2231 // and we cannot have method bss mappings without class offsets.
2232 static_assert(alignof(MethodBssMapping) == 4u, "MethodBssMapping alignment check.");
2233 DCHECK_ALIGNED(offset, 4u);
2234 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2235
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01002236 MethodBssMappingEncoder encoder(
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002237 GetInstructionSetPointerSize(oat_header_->GetInstructionSet()));
2238 size_t number_of_entries = 0u;
2239 bool first_index = true;
2240 for (uint32_t method_index : method_indexes.Indexes()) {
2241 uint32_t bss_offset = bss_method_entries_.Get(MethodReference(dex_file, method_index));
2242 if (first_index || !encoder.TryMerge(method_index, bss_offset)) {
2243 encoder.Reset(method_index, bss_offset);
2244 ++number_of_entries;
2245 first_index = false;
2246 }
2247 }
2248 DCHECK_NE(number_of_entries, 0u);
2249 offset += MethodBssMapping::ComputeSize(number_of_entries);
2250 }
2251 }
2252 // Check that all dex files targeted by method bss entries are in `*dex_files_`.
2253 CHECK_EQ(number_of_dex_files, bss_method_entry_references_.size());
2254 return offset;
2255}
2256
2257size_t OatWriter::InitOatDexFiles(size_t offset) {
2258 // Initialize offsets of oat dex files.
2259 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2260 oat_dex_file.offset_ = offset;
2261 offset += oat_dex_file.SizeOf();
2262 }
2263 return offset;
2264}
2265
Brian Carlstrome24fa612011-09-29 00:53:55 -07002266size_t OatWriter::InitOatCode(size_t offset) {
2267 // calculate the offsets within OatHeader to executable code
2268 size_t old_offset = offset;
2269 // required to be on a new page boundary
2270 offset = RoundUp(offset, kPageSize);
2271 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002272 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002273 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2274 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2275 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002276 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002277 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002278 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2279 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002280
Vladimir Marko1b404a82017-09-01 13:35:26 +01002281 #define DO_TRAMPOLINE(field, fn_name) \
2282 offset = CompiledCode::AlignCode(offset, instruction_set); \
2283 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2284 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2285 (field) = compiler_driver_->Create ## fn_name(); \
2286 if (generate_debug_info) { \
2287 debug::MethodDebugInfo info = {}; \
2288 info.trampoline_name = #fn_name; \
2289 info.isa = instruction_set; \
2290 info.is_code_address_text_relative = true; \
2291 /* Use the code offset rather than the `adjusted_offset`. */ \
2292 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2293 info.code_size = (field)->size(); \
2294 method_info_.push_back(std::move(info)); \
2295 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002296 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002297
Ian Rogers848871b2013-08-05 10:56:33 -07002298 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002299 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002300 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002301 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2302 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002303
Ian Rogers848871b2013-08-05 10:56:33 -07002304 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002305 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002306 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002307 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002308 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002309 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002310 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002311 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002312 return offset;
2313}
2314
2315size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002316 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002317 if (kOatWriterDebugOatCodeLayout) {
2318 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2319 << this << "), "
2320 << "compilation is disabled";
2321 }
2322
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002323 return offset;
2324 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002325 bool success = false;
2326
2327 {
2328 ScopedObjectAccess soa(Thread::Current());
2329
2330 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2331 success = VisitDexMethods(&layout_code_visitor);
2332 DCHECK(success);
2333
2334 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2335 this,
2336 offset,
2337 layout_code_visitor.ReleaseOrderedMethods());
2338 success = layout_reserve_code_visitor.Visit();
2339 DCHECK(success);
2340 offset = layout_reserve_code_visitor.GetOffset();
2341
2342 // Save the method order because the WriteCodeMethodVisitor will need this
2343 // order again.
2344 DCHECK(ordered_methods_ == nullptr);
2345 ordered_methods_.reset(
2346 new OrderedMethodList(
2347 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2348
2349 if (kOatWriterDebugOatCodeLayout) {
2350 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2351 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2352 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2353 LOG(INFO) << pretty_name
2354 << "@ offset "
2355 << relative_patcher_->GetOffset(ordered_method.method_reference)
2356 << " X hotness "
2357 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2358 }
2359 }
2360 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002361
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002362 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002363 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002364 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002365 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002366 DCHECK(success);
2367 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002368 }
Logan Chien8b977d32012-02-21 19:14:55 +08002369
Brian Carlstrome24fa612011-09-29 00:53:55 -07002370 return offset;
2371}
2372
Vladimir Markoaad75c62016-10-03 08:46:48 +00002373void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002374 {
2375 InitBssLayoutMethodVisitor visitor(this);
2376 bool success = VisitDexMethods(&visitor);
2377 DCHECK(success);
2378 }
2379
2380 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002381 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002382 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002383 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002384 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002385 if (!map_boot_image_tables_to_bss_ &&
2386 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002387 bss_type_entries_.empty() &&
2388 bss_string_entries_.empty()) {
2389 // Nothing to put to the .bss section.
2390 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002391 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002392
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002393 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002394 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002395 if (map_boot_image_tables_to_bss_) {
2396 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2397 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2398 }
2399 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002400
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002401 bss_methods_offset_ = bss_size_;
2402
2403 // Prepare offsets for .bss ArtMethod entries.
2404 for (auto& entry : bss_method_entries_) {
2405 DCHECK_EQ(entry.second, 0u);
2406 entry.second = bss_size_;
2407 bss_size_ += static_cast<size_t>(pointer_size);
2408 }
2409
Vladimir Markoaad75c62016-10-03 08:46:48 +00002410 bss_roots_offset_ = bss_size_;
2411
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002412 // Prepare offsets for .bss Class entries.
2413 for (auto& entry : bss_type_entries_) {
2414 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002415 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002416 bss_size_ += sizeof(GcRoot<mirror::Class>);
2417 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002418 // Prepare offsets for .bss String entries.
2419 for (auto& entry : bss_string_entries_) {
2420 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002421 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002422 bss_size_ += sizeof(GcRoot<mirror::String>);
2423 }
2424}
2425
David Srbeckybc90fd02015-04-22 19:40:27 +01002426bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002427 CHECK(write_state_ == WriteState::kWriteRoData);
2428
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002429 size_t file_offset = oat_data_offset_;
2430 off_t current_offset = out->Seek(0, kSeekCurrent);
2431 if (current_offset == static_cast<off_t>(-1)) {
2432 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2433 }
2434 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2435 size_t relative_offset = current_offset - file_offset;
2436
Vladimir Markoe079e212016-05-25 12:49:49 +01002437 // Wrap out to update checksum with each write.
2438 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2439 out = &checksum_updating_out;
2440
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002441 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2442 if (relative_offset == 0) {
2443 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002444 return false;
2445 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002446
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002447 relative_offset = WriteClasses(out, file_offset, relative_offset);
2448 if (relative_offset == 0) {
2449 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002450 return false;
2451 }
2452
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002453 relative_offset = WriteMethodBssMappings(out, file_offset, relative_offset);
2454 if (relative_offset == 0) {
2455 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002456 return false;
2457 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002458
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002459 relative_offset = WriteMaps(out, file_offset, relative_offset);
2460 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002461 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2462 return false;
2463 }
2464
2465 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2466 if (relative_offset == 0) {
2467 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002468 return false;
2469 }
2470
David Srbeckybc90fd02015-04-22 19:40:27 +01002471 // Write padding.
2472 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2473 relative_offset += size_executable_offset_alignment_;
2474 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2475 size_t expected_file_offset = file_offset + relative_offset;
2476 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2477 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2478 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2479 return 0;
2480 }
2481 DCHECK_OFFSET();
2482
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002483 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002484 return true;
2485}
2486
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002487class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
2488 public:
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002489 WriteQuickeningInfoMethodVisitor(OatWriter* writer,
2490 OutputStream* out,
2491 uint32_t offset,
2492 SafeMap<const uint8_t*, uint32_t>* offset_map)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002493 : DexMethodVisitor(writer, offset),
2494 out_(out),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002495 written_bytes_(0u),
2496 offset_map_(offset_map) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002497
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002498 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it)
2499 OVERRIDE {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002500 uint32_t method_idx = it.GetMemberIndex();
2501 CompiledMethod* compiled_method =
2502 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
2503
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002504 if (HasQuickeningInfo(compiled_method)) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002505 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002506 // Deduplication is already done on a pointer basis by the compiler driver,
2507 // so we can simply compare the pointers to find out if things are duplicated.
2508 if (offset_map_->find(map.data()) == offset_map_->end()) {
2509 uint32_t length = map.size() * sizeof(map.front());
2510 offset_map_->Put(map.data(), written_bytes_);
2511 if (!out_->WriteFully(&length, sizeof(length)) ||
2512 !out_->WriteFully(map.data(), length)) {
2513 PLOG(ERROR) << "Failed to write quickening info for "
2514 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to "
2515 << out_->GetLocation();
2516 return false;
2517 }
2518 written_bytes_ += sizeof(length) + length;
2519 offset_ += sizeof(length) + length;
2520 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002521 }
2522
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002523 return true;
2524 }
2525
2526 size_t GetNumberOfWrittenBytes() const {
2527 return written_bytes_;
2528 }
2529
2530 private:
2531 OutputStream* const out_;
2532 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002533 // Maps quickening map to its offset in the file.
2534 SafeMap<const uint8_t*, uint32_t>* offset_map_;
2535};
2536
2537class OatWriter::WriteQuickeningIndicesMethodVisitor {
2538 public:
2539 WriteQuickeningIndicesMethodVisitor(OutputStream* out,
2540 uint32_t indices_offset,
2541 const SafeMap<const uint8_t*, uint32_t>& offset_map,
2542 std::vector<uint32_t>* dex_files_offset)
2543 : out_(out),
2544 indices_offset_(indices_offset),
2545 written_bytes_(0u),
2546 dex_files_offset_(dex_files_offset),
2547 offset_map_(offset_map) {}
2548
2549 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files, const CompilerDriver& driver) {
2550 for (const DexFile* dex_file : dex_files) {
2551 // Record the offset for this current dex file. It will be written in the vdex file
2552 // later.
2553 dex_files_offset_->push_back(indices_offset_ + GetNumberOfWrittenBytes());
2554 const size_t class_def_count = dex_file->NumClassDefs();
2555 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2556 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2557 const uint8_t* class_data = dex_file->GetClassData(class_def);
2558 if (class_data == nullptr) {
2559 continue;
2560 }
2561 for (ClassDataItemIterator class_it(*dex_file, class_data);
2562 class_it.HasNext();
2563 class_it.Next()) {
2564 if (!class_it.IsAtMethod()) {
2565 continue;
2566 }
2567 uint32_t method_idx = class_it.GetMemberIndex();
2568 CompiledMethod* compiled_method =
2569 driver.GetCompiledMethod(MethodReference(dex_file, method_idx));
2570 if (HasQuickeningInfo(compiled_method)) {
2571 uint32_t code_item_offset = class_it.GetMethodCodeItemOffset();
2572 uint32_t offset = offset_map_.Get(compiled_method->GetVmapTable().data());
2573 if (!out_->WriteFully(&code_item_offset, sizeof(code_item_offset)) ||
2574 !out_->WriteFully(&offset, sizeof(offset))) {
2575 PLOG(ERROR) << "Failed to write quickening info for "
2576 << dex_file->PrettyMethod(method_idx) << " to "
2577 << out_->GetLocation();
2578 return false;
2579 }
2580 written_bytes_ += sizeof(code_item_offset) + sizeof(offset);
2581 }
2582 }
2583 }
2584 }
2585 return true;
2586 }
2587
2588 size_t GetNumberOfWrittenBytes() const {
2589 return written_bytes_;
2590 }
2591
2592 private:
2593 OutputStream* const out_;
2594 const uint32_t indices_offset_;
2595 size_t written_bytes_;
2596 std::vector<uint32_t>* dex_files_offset_;
2597 // Maps quickening map to its offset in the file.
2598 const SafeMap<const uint8_t*, uint32_t>& offset_map_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002599};
2600
2601bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
2602 if (!kIsVdexEnabled) {
2603 return true;
2604 }
2605
2606 size_t initial_offset = vdex_size_;
2607 size_t start_offset = RoundUp(initial_offset, 4u);
2608
2609 vdex_size_ = start_offset;
2610 vdex_quickening_info_offset_ = vdex_size_;
2611 size_quickening_info_alignment_ = start_offset - initial_offset;
2612
2613 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2614 if (actual_offset != static_cast<off_t>(start_offset)) {
2615 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2616 << " Expected: " << start_offset
2617 << " Output: " << vdex_out->GetLocation();
2618 return false;
2619 }
2620
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002621 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002622 std::vector<uint32_t> dex_files_indices;
2623 SafeMap<const uint8_t*, uint32_t> offset_map;
2624 WriteQuickeningInfoMethodVisitor visitor1(this, vdex_out, start_offset, &offset_map);
2625 if (!VisitDexMethods(&visitor1)) {
2626 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2627 return false;
2628 }
2629
2630 WriteQuickeningIndicesMethodVisitor visitor2(vdex_out,
2631 visitor1.GetNumberOfWrittenBytes(),
2632 offset_map,
2633 &dex_files_indices);
2634 if (!visitor2.VisitDexMethods(*dex_files_, *compiler_driver_)) {
2635 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2636 return false;
2637 }
2638
2639 DCHECK_EQ(dex_files_->size(), dex_files_indices.size());
2640 if (!vdex_out->WriteFully(
2641 dex_files_indices.data(), sizeof(dex_files_indices[0]) * dex_files_indices.size())) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002642 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2643 return false;
2644 }
2645
2646 if (!vdex_out->Flush()) {
2647 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2648 << " File: " << vdex_out->GetLocation();
2649 return false;
2650 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002651 size_quickening_info_ = visitor1.GetNumberOfWrittenBytes() +
2652 visitor2.GetNumberOfWrittenBytes() +
2653 dex_files_->size() * sizeof(uint32_t);
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002654 } else {
2655 // We know we did not quicken.
2656 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002657 }
2658
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002659 vdex_size_ += size_quickening_info_;
2660 return true;
2661}
2662
David Brazdil5d5a36b2016-09-14 15:34:10 +01002663bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
2664 if (!kIsVdexEnabled) {
2665 return true;
2666 }
2667
2668 if (verifier_deps == nullptr) {
2669 // Nothing to write. Record the offset, but no need
2670 // for alignment.
2671 vdex_verifier_deps_offset_ = vdex_size_;
2672 return true;
2673 }
2674
2675 size_t initial_offset = vdex_size_;
2676 size_t start_offset = RoundUp(initial_offset, 4u);
2677
2678 vdex_size_ = start_offset;
2679 vdex_verifier_deps_offset_ = vdex_size_;
2680 size_verifier_deps_alignment_ = start_offset - initial_offset;
2681
2682 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2683 if (actual_offset != static_cast<off_t>(start_offset)) {
2684 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2685 << " Expected: " << start_offset
2686 << " Output: " << vdex_out->GetLocation();
2687 return false;
2688 }
2689
2690 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002691 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002692
2693 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2694 PLOG(ERROR) << "Failed to write verifier deps."
2695 << " File: " << vdex_out->GetLocation();
2696 return false;
2697 }
2698 if (!vdex_out->Flush()) {
2699 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2700 << " File: " << vdex_out->GetLocation();
2701 return false;
2702 }
2703
2704 size_verifier_deps_ = buffer.size();
2705 vdex_size_ += size_verifier_deps_;
2706 return true;
2707}
2708
David Srbeckybc90fd02015-04-22 19:40:27 +01002709bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002710 CHECK(write_state_ == WriteState::kWriteText);
2711
Vladimir Markoe079e212016-05-25 12:49:49 +01002712 // Wrap out to update checksum with each write.
2713 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2714 out = &checksum_updating_out;
2715
Vladimir Marko944da602016-02-19 12:27:55 +00002716 SetMultiOatRelativePatcherAdjustment();
2717
David Srbeckybc90fd02015-04-22 19:40:27 +01002718 const size_t file_offset = oat_data_offset_;
2719 size_t relative_offset = oat_header_->GetExecutableOffset();
2720 DCHECK_OFFSET();
2721
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002722 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002723 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002724 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002725 return false;
2726 }
2727
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002728 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2729 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002730 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002731 return false;
2732 }
2733
Vladimir Markof4da6752014-08-01 19:04:18 +01002734 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002735 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002736 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2737 return false;
2738 }
2739
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002740 if (kIsDebugBuild) {
2741 uint32_t size_total = 0;
2742 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002743 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2744 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002745
David Brazdil7b49e6c2016-09-01 11:06:18 +01002746 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002747 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002748 DO_STAT(size_dex_file_alignment_);
2749 DO_STAT(size_executable_offset_alignment_);
2750 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002751 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002752 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002753 DO_STAT(size_verifier_deps_);
2754 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002755 DO_STAT(size_quickening_info_);
2756 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002757 DO_STAT(size_interpreter_to_interpreter_bridge_);
2758 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2759 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002760 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002761 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002762 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002763 DO_STAT(size_quick_to_interpreter_bridge_);
2764 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002765 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002766 DO_STAT(size_code_);
2767 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002768 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002769 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002770 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002771 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002772 DO_STAT(size_oat_dex_file_location_size_);
2773 DO_STAT(size_oat_dex_file_location_data_);
2774 DO_STAT(size_oat_dex_file_location_checksum_);
2775 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002776 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002777 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002778 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2779 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2780 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002781 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002782 DO_STAT(size_oat_lookup_table_alignment_);
2783 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002784 DO_STAT(size_oat_class_offsets_alignment_);
2785 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002786 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002787 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002788 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002789 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002790 DO_STAT(size_method_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002791 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002792
David Brazdil7b49e6c2016-09-01 11:06:18 +01002793 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2794
2795 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2796 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002797 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002798
David Brazdil7b49e6c2016-09-01 11:06:18 +01002799 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2800 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002801
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002802 write_state_ = WriteState::kWriteHeader;
2803 return true;
2804}
2805
2806bool OatWriter::WriteHeader(OutputStream* out,
2807 uint32_t image_file_location_oat_checksum,
2808 uintptr_t image_file_location_oat_begin,
2809 int32_t image_patch_delta) {
2810 CHECK(write_state_ == WriteState::kWriteHeader);
2811
2812 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2813 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002814 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002815 CHECK_EQ(image_patch_delta, 0);
2816 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2817 } else {
2818 CHECK_ALIGNED(image_patch_delta, kPageSize);
2819 oat_header_->SetImagePatchDelta(image_patch_delta);
2820 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002821 oat_header_->UpdateChecksumWithHeaderData();
2822
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002823 const size_t file_offset = oat_data_offset_;
2824
2825 off_t current_offset = out->Seek(0, kSeekCurrent);
2826 if (current_offset == static_cast<off_t>(-1)) {
2827 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2828 return false;
2829 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002830 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002831 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2832 return false;
2833 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002834 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002835
2836 // Flush all other data before writing the header.
2837 if (!out->Flush()) {
2838 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2839 return false;
2840 }
2841 // Write the header.
2842 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002843 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002844 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2845 return false;
2846 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002847 // Flush the header data.
2848 if (!out->Flush()) {
2849 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002850 return false;
2851 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002852
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002853 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2854 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2855 return false;
2856 }
2857 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2858
2859 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002860 return true;
2861}
2862
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002863size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002864 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2865 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002866 // Class offsets are required to be 4 byte aligned.
2867 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
2868 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
2869 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
2870 return 0u;
2871 }
2872 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00002873 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002874 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002875 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002876 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002877 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002878 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002879 }
2880 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002881 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002882}
2883
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002884size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002885 const bool may_have_compiled = MayHaveCompiledMethods();
2886 if (may_have_compiled) {
2887 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
2888 }
2889 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002890 // If there are any classes, the class offsets allocation aligns the offset.
2891 DCHECK_ALIGNED(relative_offset, 4u);
2892 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002893 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002894 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00002895 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002896 relative_offset += oat_class_headers_[i].SizeOf();
2897 if (may_have_compiled) {
2898 if (!oat_classes_[i].Write(this, out)) {
2899 return 0u;
2900 }
2901 relative_offset += oat_classes_[i].SizeOf();
2902 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002903 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002904 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002905}
2906
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002907size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002908 {
2909 size_t vmap_tables_offset = relative_offset;
2910 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
2911 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2912 return 0;
2913 }
2914 relative_offset = visitor.GetOffset();
2915 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002916 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002917 {
2918 size_t method_infos_offset = relative_offset;
2919 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
2920 if (UNLIKELY(!VisitDexMethods(&visitor))) {
2921 return 0;
2922 }
2923 relative_offset = visitor.GetOffset();
2924 size_method_info_ = relative_offset - method_infos_offset;
2925 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002926
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002927 return relative_offset;
2928}
2929
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002930size_t OatWriter::WriteMethodBssMappings(OutputStream* out,
2931 size_t file_offset,
2932 size_t relative_offset) {
2933 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
2934
2935 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2936 const DexFile* dex_file = (*dex_files_)[i];
2937 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2938 auto it = bss_method_entry_references_.find(dex_file);
2939 if (it != bss_method_entry_references_.end()) {
2940 const BitVector& method_indexes = it->second;
2941 // If there are any classes, the class offsets allocation aligns the offset
2942 // and we cannot have method bss mappings without class offsets.
2943 static_assert(alignof(MethodBssMapping) == sizeof(uint32_t),
2944 "MethodBssMapping alignment check.");
2945 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
2946
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01002947 MethodBssMappingEncoder encoder(
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002948 GetInstructionSetPointerSize(oat_header_->GetInstructionSet()));
2949 // Allocate a sufficiently large MethodBssMapping.
2950 size_t number_of_method_indexes = method_indexes.NumSetBits();
2951 DCHECK_NE(number_of_method_indexes, 0u);
2952 size_t max_mappings_size = MethodBssMapping::ComputeSize(number_of_method_indexes);
2953 DCHECK_ALIGNED(max_mappings_size, sizeof(uint32_t));
2954 std::unique_ptr<uint32_t[]> storage(new uint32_t[max_mappings_size / sizeof(uint32_t)]);
2955 MethodBssMapping* mappings = new(storage.get()) MethodBssMapping(number_of_method_indexes);
2956 mappings->ClearPadding();
2957 // Encode the MethodBssMapping.
2958 auto init_it = mappings->begin();
2959 bool first_index = true;
2960 for (uint32_t method_index : method_indexes.Indexes()) {
2961 size_t bss_offset = bss_method_entries_.Get(MethodReference(dex_file, method_index));
2962 if (first_index) {
2963 first_index = false;
2964 encoder.Reset(method_index, bss_offset);
2965 } else if (!encoder.TryMerge(method_index, bss_offset)) {
2966 *init_it = encoder.GetEntry();
2967 ++init_it;
2968 encoder.Reset(method_index, bss_offset);
2969 }
2970 }
2971 // Store the last entry and shrink the mapping to the actual size.
2972 *init_it = encoder.GetEntry();
2973 ++init_it;
2974 DCHECK(init_it <= mappings->end());
2975 mappings->SetSize(std::distance(mappings->begin(), init_it));
2976 size_t mappings_size = MethodBssMapping::ComputeSize(mappings->size());
2977
2978 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
2979 DCHECK_OFFSET();
2980 if (!out->WriteFully(storage.get(), mappings_size)) {
2981 return 0u;
2982 }
2983 size_method_bss_mappings_ += mappings_size;
2984 relative_offset += mappings_size;
2985 } else {
2986 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
2987 }
2988 }
2989 return relative_offset;
2990}
2991
2992size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
2993 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2994
2995 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2996 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2997 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
2998 DCHECK_OFFSET();
2999
3000 // Write OatDexFile.
3001 if (!oat_dex_file->Write(this, out)) {
3002 return 0u;
3003 }
3004 relative_offset += oat_dex_file->SizeOf();
3005 }
3006
3007 return relative_offset;
3008}
3009
3010size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003011 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003012 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003013
Ian Rogers848871b2013-08-05 10:56:33 -07003014 #define DO_TRAMPOLINE(field) \
3015 do { \
3016 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3017 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003018 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003019 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003020 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003021 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003022 return false; \
3023 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003024 size_ ## field += (field)->size(); \
3025 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003026 DCHECK_OFFSET(); \
3027 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003028
Ian Rogers848871b2013-08-05 10:56:33 -07003029 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003030 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003031 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003032 DO_TRAMPOLINE(quick_resolution_trampoline_);
3033 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3034 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003035 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003036 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003037}
3038
Ian Rogers3d504072014-03-01 09:16:49 -08003039size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003040 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003041 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003042 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3043 // As with InitOatCodeDexFiles, also skip the writer if
3044 // compilation was disabled.
3045 if (kOatWriterDebugOatCodeLayout) {
3046 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3047 << this << "), "
3048 << "compilation is disabled";
3049 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003050
Igor Murashkin545412b2017-08-17 15:26:54 -07003051 return relative_offset;
3052 }
3053 ScopedObjectAccess soa(Thread::Current());
3054 DCHECK(ordered_methods_ != nullptr);
3055 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3056 std::move(ordered_methods_);
3057 WriteCodeMethodVisitor visitor(this,
3058 out,
3059 file_offset,
3060 relative_offset,
3061 std::move(*ordered_methods_ptr));
3062 if (UNLIKELY(!visitor.Visit())) {
3063 return 0;
3064 }
3065 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003066
Vladimir Markob163bb72015-03-31 21:49:49 +01003067 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3068 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3069 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3070
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003071 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003072}
3073
Vladimir Marko944da602016-02-19 12:27:55 +00003074bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003075 // Get the elf file offset of the oat file.
3076 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3077 if (raw_file_offset == static_cast<off_t>(-1)) {
3078 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3079 return false;
3080 }
3081 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3082 return true;
3083}
3084
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003085bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
3086 // Read the dex file header and perform minimal verification.
3087 uint8_t raw_header[sizeof(DexFile::Header)];
3088 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
3089 PLOG(ERROR) << "Failed to read dex file header. Actual: "
3090 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3091 return false;
3092 }
3093 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
3094 return false;
3095 }
3096
3097 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
3098 oat_dex_file->dex_file_size_ = header->file_size_;
3099 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
3100 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
3101 return true;
3102}
3103
3104bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
Mathieu Chartiercf76bf82017-09-25 16:22:36 -07003105 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
Mathieu Chartier292567e2017-10-12 13:24:38 -07003106 if (!valid_standard_dex_magic) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003107 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
3108 return false;
3109 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -07003110 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003111 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
3112 return false;
3113 }
3114 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
3115 if (header->file_size_ < sizeof(DexFile::Header)) {
3116 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
3117 << " File: " << location;
3118 return false;
3119 }
3120 return true;
3121}
3122
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003123bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003124 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003125
David Brazdil7b49e6c2016-09-01 11:06:18 +01003126 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003127
3128 // Write dex files.
3129 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003130 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003131 return false;
3132 }
3133 }
3134
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003135 CloseSources();
3136 return true;
3137}
3138
3139void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003140 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3141 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3142 }
3143 zipped_dex_files_.clear();
3144 zip_archives_.clear();
3145 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003146}
3147
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003148bool OatWriter::WriteDexFile(OutputStream* out,
3149 File* file,
3150 OatDexFile* oat_dex_file,
3151 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003152 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003153 return false;
3154 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003155 if (profile_compilation_info_ != nullptr ||
3156 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01003157 CHECK(!update_input_vdex) << "We should never update the input vdex when doing dexlayout";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003158 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3159 return false;
3160 }
3161 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003162 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003163 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003164 return false;
3165 }
3166 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003167 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003168 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003169 return false;
3170 }
3171 } else {
3172 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003173 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003174 return false;
3175 }
3176 }
3177
3178 // Update current size and account for the written data.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003179 if (kIsVdexEnabled) {
3180 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3181 vdex_size_ += oat_dex_file->dex_file_size_;
3182 } else {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003183 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003184 DCHECK_EQ(oat_size_, oat_dex_file->dex_file_offset_);
3185 oat_size_ += oat_dex_file->dex_file_size_;
3186 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003187 size_dex_file_ += oat_dex_file->dex_file_size_;
3188 return true;
3189}
3190
3191bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3192 // Dex files are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003193 size_t initial_offset = kIsVdexEnabled ? vdex_size_ : oat_size_;
3194 size_t start_offset = RoundUp(initial_offset, 4);
3195 size_t file_offset = kIsVdexEnabled ? start_offset : (oat_data_offset_ + start_offset);
3196 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003197
3198 // Seek to the start of the dex file and flush any pending operations in the stream.
3199 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003200 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3201 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003202 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003203 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003204 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3205 return false;
3206 }
3207 if (!out->Flush()) {
3208 PLOG(ERROR) << "Failed to flush before writing dex file."
3209 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3210 return false;
3211 }
3212 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003213 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003214 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003215 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003216 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3217 return false;
3218 }
3219
David Brazdil7b49e6c2016-09-01 11:06:18 +01003220 if (kIsVdexEnabled) {
3221 vdex_size_ = start_offset;
3222 } else {
3223 oat_size_ = start_offset;
3224 }
3225 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003226 return true;
3227}
3228
Jeff Hao608f2ce2016-10-19 11:17:11 -07003229bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3230 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3231 std::string error_msg;
3232 std::string location(oat_dex_file->GetLocation());
3233 std::unique_ptr<const DexFile> dex_file;
3234 if (oat_dex_file->source_.IsZipEntry()) {
3235 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3236 std::unique_ptr<MemMap> mem_map(
3237 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003238 if (mem_map == nullptr) {
3239 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3240 return false;
3241 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003242 dex_file = DexFileLoader::Open(location,
3243 zip_entry->GetCrc32(),
3244 std::move(mem_map),
3245 /* verify */ true,
3246 /* verify_checksum */ true,
3247 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003248 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003249 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003250 int dup_fd = dup(raw_file->Fd());
3251 if (dup_fd < 0) {
3252 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3253 return false;
3254 }
Nicolas Geoffray095c6c92017-10-19 13:59:55 +01003255 dex_file = DexFileLoader::OpenDex(
3256 dup_fd, location, /* verify */ true, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003257 } else {
3258 // The source data is a vdex file.
3259 CHECK(oat_dex_file->source_.IsRawData())
3260 << static_cast<size_t>(oat_dex_file->source_.GetType());
3261 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3262 // Note: The raw data has already been checked to contain the header
3263 // and all the data that the header specifies as the file size.
3264 DCHECK(raw_dex_file != nullptr);
3265 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3266 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3267 // Since the source may have had its layout changed, or may be quickened, don't verify it.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003268 dex_file = DexFileLoader::Open(raw_dex_file,
3269 header->file_size_,
3270 location,
3271 oat_dex_file->dex_file_location_checksum_,
3272 nullptr,
3273 /* verify */ false,
3274 /* verify_checksum */ false,
3275 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003276 }
Jeff Haode197542017-02-03 10:48:13 -08003277 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003278 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003279 return false;
3280 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003281 Options options;
3282 options.output_to_memmap_ = true;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003283 options.compact_dex_level_ = compact_dex_level_;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003284 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
3285 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
3286 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003287 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003288 return false;
3289 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07003290 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
Jeff Hao608f2ce2016-10-19 11:17:11 -07003291 // Set the checksum of the new oat dex file to be the original file's checksum.
3292 oat_dex_file->dex_file_location_checksum_ = dex_file->GetLocationChecksum();
3293 return true;
3294}
3295
David Brazdil7b49e6c2016-09-01 11:06:18 +01003296bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003297 File* file,
3298 OatDexFile* oat_dex_file,
3299 ZipEntry* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003300 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
3301 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003302
3303 // Extract the dex file and get the extracted size.
3304 std::string error_msg;
3305 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3306 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3307 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3308 return false;
3309 }
3310 if (file->Flush() != 0) {
3311 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3312 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3313 return false;
3314 }
3315 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3316 if (extracted_end == static_cast<off_t>(-1)) {
3317 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3318 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3319 return false;
3320 }
3321 if (extracted_end < static_cast<off_t>(start_offset)) {
3322 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3323 << " Start: " << start_offset
3324 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3325 return false;
3326 }
3327 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3328 if (extracted_size < sizeof(DexFile::Header)) {
3329 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3330 << extracted_size << " File: " << oat_dex_file->GetLocation();
3331 return false;
3332 }
3333
3334 // Read the dex file header and extract required data to OatDexFile.
3335 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3336 if (actual_offset != static_cast<off_t>(start_offset)) {
3337 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3338 << " Expected: " << start_offset
3339 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3340 return false;
3341 }
3342 if (!ReadDexFileHeader(file, oat_dex_file)) {
3343 return false;
3344 }
3345 if (extracted_size < oat_dex_file->dex_file_size_) {
3346 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3347 << " file size from header: " << oat_dex_file->dex_file_size_
3348 << " File: " << oat_dex_file->GetLocation();
3349 return false;
3350 }
3351
3352 // Override the checksum from header with the CRC from ZIP entry.
3353 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
3354
3355 // Seek both file and stream to the end offset.
3356 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3357 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3358 if (actual_offset != static_cast<off_t>(end_offset)) {
3359 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3360 << " Expected: " << end_offset
3361 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3362 return false;
3363 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003364 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003365 if (actual_offset != static_cast<off_t>(end_offset)) {
3366 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3367 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3368 return false;
3369 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003370 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003371 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3372 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3373 return false;
3374 }
3375
3376 // If we extracted more than the size specified in the header, truncate the file.
3377 if (extracted_size > oat_dex_file->dex_file_size_) {
3378 if (file->SetLength(end_offset) != 0) {
3379 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003380 << " File: " << oat_dex_file->GetLocation()
3381 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003382 return false;
3383 }
3384 }
3385
3386 return true;
3387}
3388
David Brazdil7b49e6c2016-09-01 11:06:18 +01003389bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003390 File* file,
3391 OatDexFile* oat_dex_file,
3392 File* dex_file) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003393 size_t start_offset = kIsVdexEnabled ? vdex_size_ : oat_data_offset_ + oat_size_;
3394 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003395
3396 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3397 if (input_offset != static_cast<off_t>(0)) {
3398 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3399 << " Expected: 0"
3400 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3401 return false;
3402 }
3403 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
3404 return false;
3405 }
3406
3407 // Copy the input dex file using sendfile().
3408 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3409 PLOG(ERROR) << "Failed to copy dex file to oat file."
3410 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3411 return false;
3412 }
3413 if (file->Flush() != 0) {
3414 PLOG(ERROR) << "Failed to flush dex file."
3415 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3416 return false;
3417 }
3418
3419 // Check file position and seek the stream to the end offset.
3420 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3421 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3422 if (actual_offset != static_cast<off_t>(end_offset)) {
3423 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3424 << " Expected: " << end_offset
3425 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3426 return false;
3427 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003428 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003429 if (actual_offset != static_cast<off_t>(end_offset)) {
3430 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3431 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3432 return false;
3433 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003434 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003435 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3436 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3437 return false;
3438 }
3439
3440 return true;
3441}
3442
David Brazdil7b49e6c2016-09-01 11:06:18 +01003443bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003444 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003445 const uint8_t* dex_file,
3446 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003447 // Note: The raw data has already been checked to contain the header
3448 // and all the data that the header specifies as the file size.
3449 DCHECK(dex_file != nullptr);
3450 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3451 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3452
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003453 if (update_input_vdex) {
3454 // The vdex already contains the dex code, no need to write it again.
3455 } else {
3456 if (!out->WriteFully(dex_file, header->file_size_)) {
3457 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3458 << " to " << out->GetLocation();
3459 return false;
3460 }
3461 if (!out->Flush()) {
3462 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3463 << " File: " << oat_dex_file->GetLocation();
3464 return false;
3465 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003466 }
3467
3468 // Update dex file size and resize class offsets in the OatDexFile.
3469 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003470 // Note: For vdex, the checksum is copied from the existing vdex file.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003471 oat_dex_file->dex_file_size_ = header->file_size_;
3472 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
3473 return true;
3474}
3475
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003476bool OatWriter::OpenDexFiles(
3477 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003478 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003479 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
3480 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3481 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3482
3483 if (oat_dex_files_.empty()) {
3484 // Nothing to do.
3485 return true;
3486 }
3487
3488 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003489 size_t length = kIsVdexEnabled ? (vdex_size_ - map_offset) : (oat_size_ - map_offset);
3490
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003491 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003492 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3493 length,
3494 PROT_READ | PROT_WRITE,
3495 MAP_SHARED,
3496 file->Fd(),
3497 kIsVdexEnabled ? map_offset : (oat_data_offset_ + map_offset),
3498 /* low_4gb */ false,
3499 file->GetPath().c_str(),
3500 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003501 if (dex_files_map == nullptr) {
3502 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3503 << " error: " << error_msg;
3504 return false;
3505 }
3506 std::vector<std::unique_ptr<const DexFile>> dex_files;
3507 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3508 // Make sure no one messed with input files while we were copying data.
3509 // At the very least we need consistent file size and number of class definitions.
3510 const uint8_t* raw_dex_file =
3511 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
3512 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
3513 // Note: ValidateDexFileHeader() already logged an error message.
3514 LOG(ERROR) << "Failed to verify written dex file header!"
3515 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3516 << " ~ " << static_cast<const void*>(raw_dex_file);
3517 return false;
3518 }
3519 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3520 if (header->file_size_ != oat_dex_file.dex_file_size_) {
3521 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
3522 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3523 << " Output: " << file->GetPath();
3524 return false;
3525 }
3526 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
3527 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
3528 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
3529 << " Output: " << file->GetPath();
3530 return false;
3531 }
3532
3533 // Now, open the dex file.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003534 dex_files.emplace_back(DexFileLoader::Open(raw_dex_file,
3535 oat_dex_file.dex_file_size_,
3536 oat_dex_file.GetLocation(),
3537 oat_dex_file.dex_file_location_checksum_,
3538 /* oat_dex_file */ nullptr,
3539 verify,
3540 verify,
3541 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003542 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003543 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3544 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003545 return false;
3546 }
3547 }
3548
3549 *opened_dex_files_map = std::move(dex_files_map);
3550 *opened_dex_files = std::move(dex_files);
3551 return true;
3552}
3553
3554bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003555 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003556 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3557 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3558
David Brazdil7b49e6c2016-09-01 11:06:18 +01003559 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3560 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3561 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3562 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3563 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3564 return false;
3565 }
3566
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003567 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3568 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3569 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003570 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3571
3572 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3573 oat_dex_file->class_offsets_.empty()) {
3574 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003575 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003576
3577 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3578 if (table_size == 0u) {
3579 continue;
3580 }
3581
3582 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003583 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003584 const DexFile& dex_file = *opened_dex_files[i];
3585 {
3586 std::unique_ptr<TypeLookupTable> type_lookup_table =
3587 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3588 type_lookup_table_oat_dex_files_.push_back(
3589 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3590 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3591 }
3592 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003593
3594 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003595 size_t initial_offset = oat_size_;
3596 size_t rodata_offset = RoundUp(initial_offset, 4);
3597 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003598
3599 if (padding_size != 0u) {
3600 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003601 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003602 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3603 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003604 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003605 return false;
3606 }
3607 }
3608
3609 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003610 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003611 DCHECK_EQ(table_size, table->RawDataLength());
3612
David Brazdil7b49e6c2016-09-01 11:06:18 +01003613 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003614 PLOG(ERROR) << "Failed to write lookup table."
3615 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003616 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003617 return false;
3618 }
3619
3620 oat_dex_file->lookup_table_offset_ = rodata_offset;
3621
David Brazdil7b49e6c2016-09-01 11:06:18 +01003622 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003623 size_oat_lookup_table_ += table_size;
3624 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003625 }
3626
David Brazdil7b49e6c2016-09-01 11:06:18 +01003627 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003628 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003629 << " File: " << oat_rodata->GetLocation();
3630 return false;
3631 }
3632
3633 return true;
3634}
3635
Mathieu Chartier120aa282017-08-05 16:03:03 -07003636bool OatWriter::WriteDexLayoutSections(
3637 OutputStream* oat_rodata,
3638 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3639 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3640
3641 if (!kWriteDexLayoutInfo) {
3642 return true;;
3643 }
3644
3645 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3646 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3647 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3648 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3649 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3650 return false;
3651 }
3652
3653 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3654 size_t rodata_offset = oat_size_;
3655 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3656 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3657 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3658
3659 // Write dex layout section alignment bytes.
3660 const size_t padding_size =
3661 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3662 if (padding_size != 0u) {
3663 std::vector<uint8_t> buffer(padding_size, 0u);
3664 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3665 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3666 << " File: " << oat_dex_file->GetLocation()
3667 << " Output: " << oat_rodata->GetLocation();
3668 return false;
3669 }
3670 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3671 rodata_offset += padding_size;
3672 }
3673
3674 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3675 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3676 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3677 DCHECK(oat_dex_file != nullptr);
3678 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3679 sizeof(oat_dex_file->dex_sections_layout_))) {
3680 PLOG(ERROR) << "Failed to write dex layout sections."
3681 << " File: " << oat_dex_file->GetLocation()
3682 << " Output: " << oat_rodata->GetLocation();
3683 return false;
3684 }
3685 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3686 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3687 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3688 }
3689 oat_size_ = rodata_offset;
3690
3691 if (!oat_rodata->Flush()) {
3692 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3693 << " File: " << oat_rodata->GetLocation();
3694 return false;
3695 }
3696
3697 return true;
3698}
3699
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003700bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01003701 if (!kIsVdexEnabled) {
3702 return true;
3703 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003704 // Write checksums
3705 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
3706 if (actual_offset != sizeof(VdexFile::Header)) {
3707 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3708 << " File: " << vdex_out->GetLocation();
3709 return false;
3710 }
3711
3712 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3713 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3714 if (!vdex_out->WriteFully(
3715 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3716 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3717 << vdex_out->GetLocation();
3718 return false;
3719 }
3720 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3721 }
3722
3723 // Write header.
3724 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003725 if (actual_offset != 0) {
3726 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3727 << " File: " << vdex_out->GetLocation();
3728 return false;
3729 }
3730
David Brazdil5d5a36b2016-09-14 15:34:10 +01003731 DCHECK_NE(vdex_dex_files_offset_, 0u);
3732 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
3733
3734 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003735 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3736 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003737
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003738 VdexFile::Header vdex_header(oat_dex_files_.size(),
3739 dex_section_size,
3740 verifier_deps_section_size,
3741 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003742 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
3743 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003744 return false;
3745 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003746 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003747
David Brazdil5d5a36b2016-09-14 15:34:10 +01003748 if (!vdex_out->Flush()) {
3749 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3750 << " File: " << vdex_out->GetLocation();
3751 return false;
3752 }
3753
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003754 return true;
3755}
3756
Vladimir Markof4da6752014-08-01 19:04:18 +01003757bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003758 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3759}
3760
3761bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003762 static const uint8_t kPadding[] = {
3763 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3764 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003765 DCHECK_LE(size, sizeof(kPadding));
3766 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003767 return false;
3768 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003769 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01003770 return true;
3771}
3772
Vladimir Marko944da602016-02-19 12:27:55 +00003773void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3774 DCHECK(dex_files_ != nullptr);
3775 DCHECK(relative_patcher_ != nullptr);
3776 DCHECK_NE(oat_data_offset_, 0u);
3777 if (image_writer_ != nullptr && !dex_files_->empty()) {
3778 // The oat data begin may not be initialized yet but the oat file offset is ready.
3779 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3780 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3781 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01003782 }
3783}
3784
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003785OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3786 DexFileSource source,
3787 CreateTypeLookupTable create_type_lookup_table)
3788 : source_(source),
3789 create_type_lookup_table_(create_type_lookup_table),
3790 dex_file_size_(0),
3791 offset_(0),
3792 dex_file_location_size_(strlen(dex_file_location)),
3793 dex_file_location_data_(dex_file_location),
3794 dex_file_location_checksum_(0u),
3795 dex_file_offset_(0u),
3796 class_offsets_offset_(0u),
3797 lookup_table_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003798 method_bss_mapping_offset_(0u),
Mathieu Chartier120aa282017-08-05 16:03:03 -07003799 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003800 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07003801}
3802
3803size_t OatWriter::OatDexFile::SizeOf() const {
3804 return sizeof(dex_file_location_size_)
3805 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003806 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08003807 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003808 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003809 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003810 + sizeof(method_bss_mapping_offset_)
3811 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003812}
3813
3814bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3815 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003816 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003817
Vladimir Markoe079e212016-05-25 12:49:49 +01003818 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003819 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003820 return false;
3821 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003822 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003823
Vladimir Markoe079e212016-05-25 12:49:49 +01003824 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003825 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003826 return false;
3827 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003828 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003829
Vladimir Markoe079e212016-05-25 12:49:49 +01003830 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003831 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003832 return false;
3833 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003834 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003835
Vladimir Markoe079e212016-05-25 12:49:49 +01003836 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003837 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003838 return false;
3839 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003840 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003841
Vladimir Markoe079e212016-05-25 12:49:49 +01003842 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003843 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3844 return false;
3845 }
3846 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3847
Vladimir Markoe079e212016-05-25 12:49:49 +01003848 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003849 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3850 return false;
3851 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003852 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003853
Mathieu Chartier120aa282017-08-05 16:03:03 -07003854 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
3855 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
3856 return false;
3857 }
3858 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
3859
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003860 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
3861 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
3862 return false;
3863 }
3864 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
3865
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003866 return true;
3867}
3868
3869bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003870 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003871 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
3872 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003873 return false;
3874 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003875 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003876 return true;
3877}
3878
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003879OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003880 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003881 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003882 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003883 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003884 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07003885
Brian Carlstromba150c32013-08-27 17:31:03 -07003886 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
3887
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003888 method_offsets_.resize(compiled_methods_with_code);
3889 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07003890
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003891 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
3892 // We only create this instance if there are at least some compiled.
3893 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003894 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07003895 method_bitmap_size_ = method_bitmap_->GetSizeOf();
3896 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
3897 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
3898 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003899 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07003900 method_bitmap_size_ = 0;
3901 }
3902
3903 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003904 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003905 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003906 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
3907 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003908 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07003909 method_bitmap_->SetBit(i);
3910 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01003911 } else {
3912 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07003913 }
3914 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003915}
3916
Brian Carlstrom265091e2013-01-30 14:08:26 -08003917size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003918 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07003919 + method_bitmap_size_
3920 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07003921}
3922
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003923bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
3924 OutputStream* out,
3925 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08003926 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01003927 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003928 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08003929 return false;
3930 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003931 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003932
Vladimir Markoe079e212016-05-25 12:49:49 +01003933 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003934 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003935 return false;
3936 }
3937 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003938 return true;
3939}
Vladimir Marko49b0f452015-12-10 13:49:19 +00003940
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003941bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07003942 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01003943 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003944 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003945 return false;
3946 }
3947 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003948
Vladimir Markoe079e212016-05-25 12:49:49 +01003949 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003950 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07003951 return false;
3952 }
3953 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
3954 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003955
Vladimir Markoe079e212016-05-25 12:49:49 +01003956 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08003957 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003958 return false;
3959 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003960 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003961 return true;
3962}
3963
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01003964const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
3965 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01003966 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01003967 uint32_t utf16_length;
3968 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
3969 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
3970 InternTable::Utf8String string(utf16_length,
3971 utf8_data,
3972 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
3973 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
3974 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
3975 auto it = table.Find(string);
3976 if (it != table.end()) {
3977 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
3978 }
3979 }
3980 LOG(FATAL) << "Did not find boot image string " << utf8_data;
3981 UNREACHABLE();
3982}
3983
Vladimir Marko94ec2db2017-09-06 17:21:03 +01003984const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
3985 dex::TypeIndex type_idx)
3986 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
3987 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
3988 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
3989 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
3990 for (const ClassTable::ClassSet& class_set : table->classes_) {
3991 auto it = class_set.Find(pair);
3992 if (it != class_set.end()) {
3993 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
3994 }
3995 }
3996 LOG(FATAL) << "Did not find boot image class " << descriptor;
3997 UNREACHABLE();
3998}
3999
Vladimir Marko74527972016-11-29 15:57:32 +00004000} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004001} // namespace art