blob: b5c5d98c1106ad2a7e901da32e203a7c03e37f14 [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 Markof3c52b42017-11-17 17:32:12 +000048#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010049#include "linker/linker_patch.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,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000277 CreateTypeLookupTable create_type_lookup_table,
278 uint32_t dex_file_location_checksun,
279 size_t dex_file_size);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000280 OatDexFile(OatDexFile&& src) = default;
281
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000282 const char* GetLocation() const {
283 return dex_file_location_data_;
284 }
285
Vladimir Marko49b0f452015-12-10 13:49:19 +0000286 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000287 bool Write(OatWriter* oat_writer, OutputStream* out) const;
288 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
289
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100290 size_t GetClassOffsetsRawSize() const {
291 return class_offsets_.size() * sizeof(class_offsets_[0]);
292 }
293
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000294 // The source of the dex file.
295 DexFileSource source_;
296
297 // Whether to create the type lookup table.
298 CreateTypeLookupTable create_type_lookup_table_;
299
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000300 // Dex file size. Passed in the constructor, but could be
301 // overwritten by LayoutAndWriteDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000302 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000303
304 // Offset of start of OatDexFile from beginning of OatHeader. It is
305 // used to validate file position when writing.
306 size_t offset_;
307
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000308 ///// Start of data to write to vdex/oat file.
309
310 const uint32_t dex_file_location_size_;
311 const char* const dex_file_location_data_;
312
313 // The checksum of the dex file.
314 const uint32_t dex_file_location_checksum_;
315
316 // Offset of the dex file in the vdex file. Set when writing dex files in
317 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000318 uint32_t dex_file_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000319
320 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000321 uint32_t lookup_table_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000322
323 // Class and BSS offsets set in PrepareLayout.
324 uint32_t class_offsets_offset_;
Nicolas Geoffray715d6722017-11-20 22:28:46 +0000325 uint32_t method_bss_mapping_offset_;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000326 uint32_t type_bss_mapping_offset_;
327 uint32_t string_bss_mapping_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000328
329 // Offset of dex sections that will have different runtime madvise states.
330 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700331 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000332
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000333 // Data to write to a separate section. We set the length
334 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000335 dchecked_vector<uint32_t> class_offsets_;
336
Mathieu Chartier120aa282017-08-05 16:03:03 -0700337 // Dex section layout info to serialize.
338 DexLayoutSections dex_sections_layout_;
339
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000340 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000341 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000342 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
343};
344
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100345#define DCHECK_OFFSET() \
346 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
347 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
348
349#define DCHECK_OFFSET_() \
350 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
351 << "file_offset=" << file_offset << " offset_=" << offset_
352
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700353OatWriter::OatWriter(bool compiling_boot_image,
354 TimingLogger* timings,
355 ProfileCompilationInfo* info,
356 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000357 : write_state_(WriteState::kAddingDexFileSources),
358 timings_(timings),
359 raw_dex_files_(),
360 zip_archives_(),
361 zipped_dex_files_(),
362 zipped_dex_file_locations_(),
363 compiler_driver_(nullptr),
364 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800365 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000366 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100367 vdex_size_(0u),
368 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100369 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100370 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100371 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000372 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000373 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100374 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000375 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100376 bss_method_entry_references_(),
377 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000378 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000379 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100380 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100381 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700382 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100383 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000384 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700385 size_dex_file_alignment_(0),
386 size_executable_offset_alignment_(0),
387 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700388 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700389 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100390 size_verifier_deps_(0),
391 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100392 size_quickening_info_(0),
393 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700394 size_interpreter_to_interpreter_bridge_(0),
395 size_interpreter_to_compiled_code_bridge_(0),
396 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800397 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700398 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700399 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700400 size_quick_to_interpreter_bridge_(0),
401 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100402 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700403 size_code_(0),
404 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100405 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100406 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700407 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700408 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700409 size_oat_dex_file_location_size_(0),
410 size_oat_dex_file_location_data_(0),
411 size_oat_dex_file_location_checksum_(0),
412 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000413 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000414 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700415 size_oat_dex_file_dex_layout_sections_offset_(0),
416 size_oat_dex_file_dex_layout_sections_(0),
417 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100418 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000419 size_oat_dex_file_type_bss_mapping_offset_(0),
420 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000421 size_oat_lookup_table_alignment_(0),
422 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000423 size_oat_class_offsets_alignment_(0),
424 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700425 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700426 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700427 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100428 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100429 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000430 size_type_bss_mappings_(0u),
431 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000432 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700433 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700434 profile_compilation_info_(info),
435 compact_dex_level_(compact_dex_level) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000436}
437
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000438static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
439 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
440 if (!valid_standard_dex_magic) {
441 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
442 return false;
443 }
444 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
445 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
446 return false;
447 }
448 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
449 if (header->file_size_ < sizeof(DexFile::Header)) {
450 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
451 << " File: " << location;
452 return false;
453 }
454 return true;
455}
456
457static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
458 uint8_t* raw_header,
459 const char* location) {
460 // Read the dex file header and perform minimal verification.
461 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
462 PLOG(ERROR) << "Failed to read dex file header. Actual: "
463 << " File: " << location << " Output: " << file->GetPath();
464 return nullptr;
465 }
466 if (!ValidateDexFileHeader(raw_header, location)) {
467 return nullptr;
468 }
469
470 return AsUnalignedDexFileHeader(raw_header);
471}
472
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000473bool OatWriter::AddDexFileSource(const char* filename,
474 const char* location,
475 CreateTypeLookupTable create_type_lookup_table) {
476 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
477 uint32_t magic;
478 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700479 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
480 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
482 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700483 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000484 uint8_t raw_header[sizeof(DexFile::Header)];
485 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
486 if (header == nullptr) {
487 return false;
488 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 // The file is open for reading, not writing, so it's OK to let the File destructor
490 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700491 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000492 oat_dex_files_.emplace_back(/* OatDexFile */
493 location,
494 DexFileSource(raw_dex_files_.back().get()),
495 create_type_lookup_table,
496 header->checksum_,
497 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000498 } else if (IsZipMagic(magic)) {
499 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
500 return false;
501 }
502 } else {
503 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
504 return false;
505 }
506 return true;
507}
508
509// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700510bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000511 const char* location,
512 CreateTypeLookupTable create_type_lookup_table) {
513 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
514 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700515 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000516 ZipArchive* zip_archive = zip_archives_.back().get();
517 if (zip_archive == nullptr) {
518 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
519 << error_msg;
520 return false;
521 }
522 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700523 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
525 if (entry == nullptr) {
526 break;
527 }
528 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700529 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000531 // We override the checksum from header with the CRC from ZIP entry.
532 oat_dex_files_.emplace_back(/* OatDexFile */
533 full_location,
534 DexFileSource(zipped_dex_files_.back().get()),
535 create_type_lookup_table,
536 zipped_dex_files_.back()->GetCrc32(),
537 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000538 }
539 if (zipped_dex_file_locations_.empty()) {
540 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
541 return false;
542 }
543 return true;
544}
545
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000546// Add dex file source(s) from a vdex file specified by a file handle.
547bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
548 const char* location,
549 CreateTypeLookupTable create_type_lookup_table) {
550 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
551 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000552 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000553 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
554 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000555 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
556 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000557 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700558
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700559 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000560 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
561 return false;
562 }
563 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700564 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000565 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000566 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
567 oat_dex_files_.emplace_back(/* OatDexFile */
568 full_location,
569 DexFileSource(current_dex_data),
570 create_type_lookup_table,
571 vdex_file.GetLocationChecksum(i),
572 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000573 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000574
575 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
576 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
577 return false;
578 }
579
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000580 if (oat_dex_files_.empty()) {
581 LOG(ERROR) << "No dex files in vdex file created from " << location;
582 return false;
583 }
584 return true;
585}
586
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000587// Add dex file source from raw memory.
588bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
589 const char* location,
590 uint32_t location_checksum,
591 CreateTypeLookupTable create_type_lookup_table) {
592 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
593 if (data.size() < sizeof(DexFile::Header)) {
594 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
595 << data.size() << " File: " << location;
596 return false;
597 }
598 if (!ValidateDexFileHeader(data.data(), location)) {
599 return false;
600 }
601 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
602 if (data.size() < header->file_size_) {
603 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
604 << " file size from header: " << header->file_size_ << " File: " << location;
605 return false;
606 }
607
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000608 oat_dex_files_.emplace_back(/* OatDexFile */
609 location,
610 DexFileSource(data.data()),
611 create_type_lookup_table,
612 location_checksum,
613 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000614 return true;
615}
616
Calin Juravle1ce70852017-06-28 10:59:03 -0700617dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
618 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000619 locations.reserve(oat_dex_files_.size());
620 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
621 locations.push_back(oat_dex_file.GetLocation());
622 }
623 return locations;
624}
625
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700626bool OatWriter::MayHaveCompiledMethods() const {
627 return CompilerFilter::IsAnyCompilationEnabled(
628 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
629}
630
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000631bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100632 File* vdex_file,
633 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000634 InstructionSet instruction_set,
635 const InstructionSetFeatures* instruction_set_features,
636 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800637 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000638 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000639 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
640 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
641 CHECK(write_state_ == WriteState::kAddingDexFileSources);
642
David Brazdil7b49e6c2016-09-01 11:06:18 +0100643 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
644 if (!RecordOatDataOffset(oat_rodata)) {
645 return false;
646 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000647
648 std::unique_ptr<MemMap> dex_files_map;
649 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100650
651 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000652
653 // Reserve space for Vdex header and checksums.
654 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100655 oat_size_ = InitOatHeader(instruction_set,
656 instruction_set_features,
657 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
658 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100659
660 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
661
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000662 std::unique_ptr<BufferedOutputStream> vdex_out =
663 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
664 // Write DEX files into VDEX, mmap and open them.
665 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
666 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
667 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000668 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000669
Mathieu Chartier120aa282017-08-05 16:03:03 -0700670 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000671 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
672 return false;
673 }
674
Mathieu Chartier120aa282017-08-05 16:03:03 -0700675 // Write dex layout sections into the oat file.
676 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
677 return false;
678 }
679
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000680 *opened_dex_files_map = std::move(dex_files_map);
681 *opened_dex_files = std::move(dex_files);
682 write_state_ = WriteState::kPrepareLayout;
683 return true;
684}
685
Vladimir Marko74527972016-11-29 15:57:32 +0000686void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000687 CHECK(write_state_ == WriteState::kPrepareLayout);
688
Vladimir Marko944da602016-02-19 12:27:55 +0000689 relative_patcher_ = relative_patcher;
690 SetMultiOatRelativePatcherAdjustment();
691
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000692 if (compiling_boot_image_) {
693 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800694 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100695 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000696 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100697
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100698 {
699 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
700 InitBssLayout(instruction_set);
701 }
702
David Brazdil7b49e6c2016-09-01 11:06:18 +0100703 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800704 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100705 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
706 offset = InitClassOffsets(offset);
707 }
708 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000709 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800710 offset = InitOatClasses(offset);
711 }
712 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000713 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
714 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100715 }
716 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000717 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 offset = InitOatMaps(offset);
719 }
720 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100721 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
722 oat_header_->SetOatDexFilesOffset(offset);
723 offset = InitOatDexFiles(offset);
724 }
725 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000726 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800727 offset = InitOatCode(offset);
728 }
729 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000730 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800731 offset = InitOatCodeDexFiles(offset);
732 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100733 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100734 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100735
Brian Carlstrome24fa612011-09-29 00:53:55 -0700736 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800737 if (compiling_boot_image_) {
738 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000739 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800740 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000741
742 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700743}
744
Ian Rogers0571d352011-11-03 19:51:38 -0700745OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700746}
747
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100748class OatWriter::DexMethodVisitor {
749 public:
750 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100751 : writer_(writer),
752 offset_(offset),
753 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700754 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755
756 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
757 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700758 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100759 dex_file_ = dex_file;
760 class_def_index_ = class_def_index;
761 return true;
762 }
763
764 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
765
766 virtual bool EndClass() {
767 if (kIsDebugBuild) {
768 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700769 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100770 }
771 return true;
772 }
773
774 size_t GetOffset() const {
775 return offset_;
776 }
777
778 protected:
779 virtual ~DexMethodVisitor() { }
780
781 OatWriter* const writer_;
782
783 // The offset is usually advanced for each visited method by the derived class.
784 size_t offset_;
785
786 // The dex file and class def index are set in StartClass().
787 const DexFile* dex_file_;
788 size_t class_def_index_;
789};
790
791class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
792 public:
793 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100794 : DexMethodVisitor(writer, offset),
795 oat_class_index_(0u),
796 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100797
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100798 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100799 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700800 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
801 // There are no oat classes if there aren't any compiled methods.
802 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
803 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100804 method_offsets_index_ = 0u;
805 return true;
806 }
807
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100808 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100809 ++oat_class_index_;
810 return DexMethodVisitor::EndClass();
811 }
812
813 protected:
814 size_t oat_class_index_;
815 size_t method_offsets_index_;
816};
817
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100818static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000819 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100820}
821
822static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000823 // The dextodexcompiler puts the quickening info table into the CompiledMethod
824 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100825 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
826}
827
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100828class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
829 public:
830 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
831 : DexMethodVisitor(writer, /* offset */ 0u) {}
832
833 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
834 const ClassDataItemIterator& it) OVERRIDE {
835 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
836 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
837 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100838 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100839 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
840 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
841 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000842 AddBssReference(target_method,
843 target_method.dex_file->NumMethodIds(),
844 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100845 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
846 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000847 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
848 AddBssReference(target_type,
849 target_type.dex_file->NumTypeIds(),
850 &writer_->bss_type_entry_references_);
851 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100852 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000853 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
854 AddBssReference(target_string,
855 target_string.dex_file->NumStringIds(),
856 &writer_->bss_string_entry_references_);
857 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100858 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
859 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100860 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100861 }
862 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100863 } else {
864 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100865 }
866 return true;
867 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000868
869 private:
870 void AddBssReference(const DexFileReference& ref,
871 size_t number_of_indexes,
872 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
873 // We currently support inlining of throwing instructions only when they originate in the
874 // same dex file as the outer method. All .bss references are used by throwing instructions.
875 DCHECK_EQ(dex_file_, ref.dex_file);
876
877 auto refs_it = references->find(ref.dex_file);
878 if (refs_it == references->end()) {
879 refs_it = references->Put(
880 ref.dex_file,
881 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
882 refs_it->second.ClearAllBits();
883 }
884 refs_it->second.SetBit(ref.index);
885 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100886};
887
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100888class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
889 public:
890 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100891 : DexMethodVisitor(writer, offset),
892 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100893 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000894 size_t num_classes = 0u;
895 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
896 num_classes += oat_dex_file.class_offsets_.size();
897 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700898 // If we aren't compiling only reserve headers.
899 writer_->oat_class_headers_.reserve(num_classes);
900 if (writer->MayHaveCompiledMethods()) {
901 writer->oat_classes_.reserve(num_classes);
902 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100904 // If there are any classes, the class offsets allocation aligns the offset.
905 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100906 }
907
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100908 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100909 DexMethodVisitor::StartClass(dex_file, class_def_index);
910 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100911 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100912 return true;
913 }
914
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300915 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100916 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100917 // Fill in the compiled_methods_ array for methods that have a
918 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100919 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920 // OatMethodOffsets for the compiled methods.
921 uint32_t method_idx = it.GetMemberIndex();
922 CompiledMethod* compiled_method =
923 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
924 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100925 if (HasCompiledCode(compiled_method)) {
926 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100927 }
928 return true;
929 }
930
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100931 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100932 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100933 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700934 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
935 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700936 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
937 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700938 // The oat class status is used only for verification of resolved classes,
939 // so use kStatusErrorResolved whether the class was resolved or unresolved
940 // during compile-time verification.
941 status = mirror::Class::kStatusErrorResolved;
942 } else {
943 status = mirror::Class::kStatusNotReady;
944 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100945 }
946
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700947 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100948 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700949 compiled_methods_.size(),
950 status);
951 OatClassHeader& header = writer_->oat_class_headers_.back();
952 offset_ += header.SizeOf();
953 if (writer_->MayHaveCompiledMethods()) {
954 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100955 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700956 header.type_);
957 offset_ += writer_->oat_classes_.back().SizeOf();
958 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 return DexMethodVisitor::EndClass();
960 }
961
962 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000963 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100964 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100965};
966
Igor Murashkin545412b2017-08-17 15:26:54 -0700967// CompiledMethod + metadata required to do ordered method layout.
968//
969// See also OrderedMethodVisitor.
970struct OatWriter::OrderedMethodData {
971 ProfileCompilationInfo::MethodHotness method_hotness;
972 OatClass* oat_class;
973 CompiledMethod* compiled_method;
974 MethodReference method_reference;
975 size_t method_offsets_index;
976
977 size_t class_def_index;
978 uint32_t access_flags;
979 const DexFile::CodeItem* code_item;
980
981 // A value of -1 denotes missing debug info
982 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
983 // Index into writer_->method_info_
984 size_t debug_info_idx;
985
986 bool HasDebugInfo() const {
987 return debug_info_idx != kDebugInfoIdxInvalid;
988 }
989
990 // Bin each method according to the profile flags.
991 //
992 // Groups by e.g.
993 // -- not hot at all
994 // -- hot
995 // -- hot and startup
996 // -- hot and post-startup
997 // -- hot and startup and poststartup
998 // -- startup
999 // -- startup and post-startup
1000 // -- post-startup
1001 //
1002 // (See MethodHotness enum definition for up-to-date binning order.)
1003 bool operator<(const OrderedMethodData& other) const {
1004 if (kOatWriterForceOatCodeLayout) {
1005 // Development flag: Override default behavior by sorting by name.
1006
1007 std::string name = method_reference.PrettyMethod();
1008 std::string other_name = other.method_reference.PrettyMethod();
1009 return name < other_name;
1010 }
1011
1012 // Use the profile's method hotness to determine sort order.
1013 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1014 return true;
1015 }
1016
1017 // Default: retain the original order.
1018 return false;
1019 }
1020
1021 private:
1022 // Used to determine relative order for OAT code layout when determining
1023 // binning.
1024 size_t GetMethodHotnessOrder() const {
1025 bool hotness[] = {
1026 method_hotness.IsHot(),
1027 method_hotness.IsStartup(),
1028 method_hotness.IsPostStartup()
1029 };
1030
1031
1032 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1033 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1034 // time that memory is referenced in the process.
1035
1036 size_t hotness_bits = 0;
1037 for (size_t i = 0; i < arraysize(hotness); ++i) {
1038 if (hotness[i]) {
1039 hotness_bits |= (1 << i);
1040 }
1041 }
1042
1043 if (kIsDebugBuild) {
1044 // Check for bins that are always-empty given a real profile.
1045 if (method_hotness.IsHot() &&
1046 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1047 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001048 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1049 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001050 // This is not fatal, so only warn.
1051 }
1052 }
1053
1054 return hotness_bits;
1055 }
1056};
1057
1058// Given a queue of CompiledMethod in some total order,
1059// visit each one in that order.
1060class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001061 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001062 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1063 : ordered_methods_(std::move(ordered_methods)) {
1064 }
1065
1066 virtual ~OrderedMethodVisitor() {}
1067
1068 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1069 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1070 if (!VisitStart()) {
1071 return false;
1072 }
1073
1074 for (const OrderedMethodData& method_data : ordered_methods_) {
1075 if (!VisitMethod(method_data)) {
1076 return false;
1077 }
1078 }
1079
1080 return VisitComplete();
1081 }
1082
1083 // Invoked once at the beginning, prior to visiting anything else.
1084 //
1085 // Return false to abort further visiting.
1086 virtual bool VisitStart() { return true; }
1087
1088 // Invoked repeatedly in the order specified by `ordered_methods`.
1089 //
1090 // Return false to short-circuit and to stop visiting further methods.
1091 virtual bool VisitMethod(const OrderedMethodData& method_data)
1092 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1093
1094 // Invoked once at the end, after every other method has been successfully visited.
1095 //
1096 // Return false to indicate the overall `Visit` has failed.
1097 virtual bool VisitComplete() = 0;
1098
1099 OrderedMethodList ReleaseOrderedMethods() {
1100 return std::move(ordered_methods_);
1101 }
1102
1103 private:
1104 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1105 // Methods can be inserted more than once in case of duplicated methods.
1106 OrderedMethodList ordered_methods_;
1107};
1108
1109// Visit every compiled method in order to determine its order within the OAT file.
1110// Methods from the same class do not need to be adjacent in the OAT code.
1111class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1112 public:
1113 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1114 : OatDexMethodVisitor(writer, offset) {
1115 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001116
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001117 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001118 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001119 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001120 }
1121
Igor Murashkin545412b2017-08-17 15:26:54 -07001122 bool VisitMethod(size_t class_def_method_index,
1123 const ClassDataItemIterator& it)
1124 OVERRIDE
1125 REQUIRES_SHARED(Locks::mutator_lock_) {
1126 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1127
Vladimir Marko49b0f452015-12-10 13:49:19 +00001128 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001129 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1130
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001131 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001132 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001133
Igor Murashkin545412b2017-08-17 15:26:54 -07001134 {
1135 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1136 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1137 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001138
Igor Murashkin545412b2017-08-17 15:26:54 -07001139 // Debug method info must be pushed in the original order
1140 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1141 // ElfCompilationUnitWriter::Write requires this.
1142 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1143 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1144 writer_->method_info_.push_back(info);
1145
1146 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1147 // once we know the offsets.
1148 //
1149 // Store the index into writer_->method_info_ since future push-backs
1150 // could reallocate and change the underlying data address.
1151 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001152 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001153 }
1154
1155 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1156
1157 // Lookup method hotness from profile, if available.
1158 // Otherwise assume a default of none-hotness.
1159 ProfileCompilationInfo::MethodHotness method_hotness =
1160 writer_->profile_compilation_info_ != nullptr
1161 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1162 : ProfileCompilationInfo::MethodHotness();
1163
1164 // Handle duplicate methods by pushing them repeatedly.
1165 OrderedMethodData method_data = {
1166 method_hotness,
1167 oat_class,
1168 compiled_method,
1169 method_ref,
1170 method_offsets_index_,
1171 class_def_index_,
1172 it.GetMethodAccessFlags(),
1173 it.GetMethodCodeItem(),
1174 debug_info_idx
1175 };
1176 ordered_methods_.push_back(method_data);
1177
1178 method_offsets_index_++;
1179 }
1180
1181 return true;
1182 }
1183
1184 OrderedMethodList ReleaseOrderedMethods() {
1185 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1186 // Sort by the method ordering criteria (in OrderedMethodData).
1187 // Since most methods will have the same ordering criteria,
1188 // we preserve the original insertion order within the same sort order.
1189 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1190 } else {
1191 // The profile-less behavior is as if every method had 0 hotness
1192 // associated with it.
1193 //
1194 // Since sorting all methods with hotness=0 should give back the same
1195 // order as before, don't do anything.
1196 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1197 }
1198
1199 return std::move(ordered_methods_);
1200 }
1201
1202 private:
1203 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1204 // Methods can be inserted more than once in case of duplicated methods.
1205 OrderedMethodList ordered_methods_;
1206};
1207
1208// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1209class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1210 public:
1211 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1212 size_t offset,
1213 OrderedMethodList ordered_methods)
1214 : LayoutReserveOffsetCodeMethodVisitor(writer,
1215 offset,
1216 writer->GetCompilerDriver()->GetCompilerOptions(),
1217 std::move(ordered_methods)) {
1218 }
1219
1220 virtual bool VisitComplete() OVERRIDE {
1221 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1222 if (generate_debug_info_) {
1223 std::vector<debug::MethodDebugInfo> thunk_infos =
1224 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1225 writer_->method_info_.insert(writer_->method_info_.end(),
1226 std::make_move_iterator(thunk_infos.begin()),
1227 std::make_move_iterator(thunk_infos.end()));
1228 }
1229 return true;
1230 }
1231
1232 virtual bool VisitMethod(const OrderedMethodData& method_data)
1233 OVERRIDE
1234 REQUIRES_SHARED(Locks::mutator_lock_) {
1235 OatClass* oat_class = method_data.oat_class;
1236 CompiledMethod* compiled_method = method_data.compiled_method;
1237 const MethodReference& method_ref = method_data.method_reference;
1238 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1239 size_t class_def_index = method_data.class_def_index;
1240 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001241 bool has_debug_info = method_data.HasDebugInfo();
1242 size_t debug_info_idx = method_data.debug_info_idx;
1243
1244 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1245
1246 // Derived from CompiledMethod.
1247 uint32_t quick_code_offset = 0;
1248
1249 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1250 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1251 uint32_t thumb_offset = compiled_method->CodeDelta();
1252
1253 // Deduplicate code arrays if we are not producing debuggable code.
1254 bool deduped = true;
1255 if (debuggable_) {
1256 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1257 if (quick_code_offset != 0u) {
1258 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1259 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001260 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001261 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1262 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001263 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001264 } else {
1265 quick_code_offset = dedupe_map_.GetOrCreate(
1266 compiled_method,
1267 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1268 deduped = false;
1269 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1270 });
1271 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001272
Igor Murashkin545412b2017-08-17 15:26:54 -07001273 if (code_size != 0) {
1274 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1275 // TODO: Should this be a hard failure?
1276 LOG(WARNING) << "Multiple definitions of "
1277 << method_ref.dex_file->PrettyMethod(method_ref.index)
1278 << " offsets " << relative_patcher_->GetOffset(method_ref)
1279 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001280 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001281 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1282 }
1283 }
1284
1285 // Update quick method header.
1286 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1287 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1288 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1289 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1290 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1291 // to 0-offset and we need to adjust it by code_offset.
1292 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001293 CHECK(!compiled_method->GetQuickCode().empty());
1294 // If the code is compiled, we write the offset of the stack map relative
1295 // to the code.
1296 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001297 vmap_table_offset += code_offset;
1298 DCHECK_LT(vmap_table_offset, code_offset);
1299 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001300 if (method_info_offset != 0u) {
1301 method_info_offset += code_offset;
1302 DCHECK_LT(method_info_offset, code_offset);
1303 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001304 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1305 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1306 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1307 *method_header = OatQuickMethodHeader(vmap_table_offset,
1308 method_info_offset,
1309 frame_size_in_bytes,
1310 core_spill_mask,
1311 fp_spill_mask,
1312 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001313
Igor Murashkin545412b2017-08-17 15:26:54 -07001314 if (!deduped) {
1315 // Update offsets. (Checksum is updated when writing.)
1316 offset_ += sizeof(*method_header); // Method header is prepended before code.
1317 offset_ += code_size;
1318 // Record absolute patch locations.
1319 if (!compiled_method->GetPatches().empty()) {
1320 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1321 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1322 if (!patch.IsPcRelative()) {
1323 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001324 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001325 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001326 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001327 }
1328
Igor Murashkin545412b2017-08-17 15:26:54 -07001329 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1330 if (generate_debug_info_ && code_size != 0) {
1331 DCHECK(has_debug_info);
1332
1333 bool has_code_info = method_header->IsOptimized();
1334 // Record debug information for this function if we are doing that.
1335 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1336 DCHECK(info.trampoline_name.empty());
1337 info.dex_file = method_ref.dex_file;
1338 info.class_def_index = class_def_index;
1339 info.dex_method_index = method_ref.index;
1340 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001341 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1342 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001343 info.isa = compiled_method->GetInstructionSet();
1344 info.deduped = deduped;
1345 info.is_native_debuggable = native_debuggable_;
1346 info.is_optimized = method_header->IsOptimized();
1347 info.is_code_address_text_relative = true;
1348 info.code_address = code_offset - executable_offset_;
1349 info.code_size = code_size;
1350 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1351 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1352 info.cfi = compiled_method->GetCFIInfo();
1353 } else {
1354 DCHECK(!has_debug_info);
1355 }
1356
1357 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1358 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1359 offsets->code_offset_ = quick_code_offset;
1360
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001361 return true;
1362 }
1363
Igor Murashkin545412b2017-08-17 15:26:54 -07001364 size_t GetOffset() const {
1365 return offset_;
1366 }
1367
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001368 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001369 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1370 size_t offset,
1371 const CompilerOptions& compiler_options,
1372 OrderedMethodList ordered_methods)
1373 : OrderedMethodVisitor(std::move(ordered_methods)),
1374 writer_(writer),
1375 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001376 relative_patcher_(writer->relative_patcher_),
1377 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1378 debuggable_(compiler_options.GetDebuggable()),
1379 native_debuggable_(compiler_options.GetNativeDebuggable()),
1380 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1381 writer->absolute_patch_locations_.reserve(
1382 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1383 }
1384
Vladimir Marko20f85592015-03-19 10:07:02 +00001385 struct CodeOffsetsKeyComparator {
1386 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001387 // Code is deduplicated by CompilerDriver, compare only data pointers.
1388 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1389 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001390 }
1391 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001392 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1393 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001394 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001395 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1396 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1397 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001398 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1399 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001400 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001401 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1402 return rhs->IsIntrinsic();
1403 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001404 return false;
1405 }
1406 };
1407
David Srbecky009e2a62015-04-15 02:46:30 +01001408 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001409 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001410 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001411 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001412 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1413 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001414 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1415 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1416 }
1417
Igor Murashkin545412b2017-08-17 15:26:54 -07001418 OatWriter* writer_;
1419
1420 // Offset of the code of the compiled methods.
1421 size_t offset_;
1422
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 // Deduplication is already done on a pointer basis by the compiler driver,
1424 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001425 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001426
Vladimir Marko1b404a82017-09-01 13:35:26 +01001427 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001428 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001429 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001430 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001431 const bool native_debuggable_;
1432 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001433};
1434
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001435class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1436 public:
1437 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001438 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001439
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001440 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001441 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001442 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001443 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1444
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001445 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001446 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001447 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001448
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001449 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1450 uint32_t map_size = map.size() * sizeof(map[0]);
1451 if (map_size != 0u) {
1452 size_t offset = dedupe_map_.GetOrCreate(
1453 map.data(),
1454 [this, map_size]() {
1455 uint32_t new_offset = offset_;
1456 offset_ += map_size;
1457 return new_offset;
1458 });
1459 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1460 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1461 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001462 }
1463 ++method_offsets_index_;
1464 }
1465
1466 return true;
1467 }
1468
1469 private:
1470 // Deduplication is already done on a pointer basis by the compiler driver,
1471 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001472 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001473};
1474
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001475class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1476 public:
1477 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1478
1479 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001480 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001481 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1482 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1483
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001484 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001485 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1486 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1487 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1488 const uint32_t map_size = map.size() * sizeof(map[0]);
1489 if (map_size != 0u) {
1490 size_t offset = dedupe_map_.GetOrCreate(
1491 map.data(),
1492 [this, map_size]() {
1493 uint32_t new_offset = offset_;
1494 offset_ += map_size;
1495 return new_offset;
1496 });
1497 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1498 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1499 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1500 }
1501 ++method_offsets_index_;
1502 }
1503
1504 return true;
1505 }
1506
1507 private:
1508 // Deduplication is already done on a pointer basis by the compiler driver,
1509 // so we can simply compare the pointers to find out if things are duplicated.
1510 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1511};
1512
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001513class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1514 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001515 InitImageMethodVisitor(OatWriter* writer,
1516 size_t offset,
1517 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001518 : OatDexMethodVisitor(writer, offset),
1519 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001520 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001521 dex_files_(dex_files),
1522 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001523
1524 // Handle copied methods here. Copy pointer to quick code from
1525 // an origin method to a copied method only if they are
1526 // in the same oat file. If the origin and the copied methods are
1527 // in different oat files don't touch the copied method.
1528 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001529 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001530 REQUIRES_SHARED(Locks::mutator_lock_) {
1531 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1532 // Skip classes that are not in the image.
1533 if (!IsImageClass()) {
1534 return true;
1535 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001536 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001537 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1538 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1539 if (klass != nullptr) {
1540 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1541 // Find origin method. Declaring class and dex_method_idx
1542 // in the copied method should be the same as in the origin
1543 // method.
1544 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001545 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001546 declaring_class->GetDexCache(),
1547 method.GetDexMethodIndex(),
1548 pointer_size_);
1549 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001550 CHECK(!origin->IsDirect());
1551 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001552 if (IsInOatFile(&declaring_class->GetDexFile())) {
1553 const void* code_ptr =
1554 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1555 if (code_ptr == nullptr) {
1556 methods_to_process_.push_back(std::make_pair(&method, origin));
1557 } else {
1558 method.SetEntryPointFromQuickCompiledCodePtrSize(
1559 code_ptr, pointer_size_);
1560 }
1561 }
1562 }
1563 }
1564 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001565 }
1566
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001567 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001568 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001569 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001570 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001571 return true;
1572 }
1573
Vladimir Marko49b0f452015-12-10 13:49:19 +00001574 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001575 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1576
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001577 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001578 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001579 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1580 offsets = oat_class->method_offsets_[method_offsets_index_];
1581 ++method_offsets_index_;
1582 }
1583
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001584 Thread* self = Thread::Current();
1585 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001586 ArtMethod* method;
1587 if (writer_->HasBootImage()) {
1588 const InvokeType invoke_type = it.GetMethodInvokeType(
1589 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001590 // Unchecked as we hold mutator_lock_ on entry.
1591 ScopedObjectAccessUnchecked soa(self);
1592 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001593 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001594 *dex_file_,
1595 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001596 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001597 ScopedNullHandle<mirror::ClassLoader>(),
1598 nullptr,
1599 invoke_type);
1600 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001601 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001602 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001603 self->AssertPendingException();
1604 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001605 std::string dump = exc->Dump();
1606 LOG(FATAL) << dump;
1607 UNREACHABLE();
1608 }
1609 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001610 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001611 // 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 +01001612 // entrypoint. This is not fatal since we shall use a resolution method.
1613 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001614 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001615 if (method != nullptr &&
1616 compiled_method != nullptr &&
1617 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001618 method->SetEntryPointFromQuickCompiledCodePtrSize(
1619 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1620 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001621
1622 return true;
1623 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001624
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001625 // Check whether current class is image class
1626 bool IsImageClass() {
1627 const DexFile::TypeId& type_id =
1628 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1629 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1630 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1631 }
1632
1633 // Check whether specified dex file is in the compiled oat file.
1634 bool IsInOatFile(const DexFile* dex_file) {
1635 return ContainsElement(*dex_files_, dex_file);
1636 }
1637
1638 // Assign a pointer to quick code for copied methods
1639 // not handled in the method StartClass
1640 void Postprocess() {
1641 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1642 ArtMethod* method = p.first;
1643 ArtMethod* origin = p.second;
1644 const void* code_ptr =
1645 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1646 if (code_ptr != nullptr) {
1647 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1648 }
1649 }
1650 }
1651
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001652 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001653 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001654 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001655 const std::vector<const DexFile*>* dex_files_;
1656 ClassLinker* const class_linker_;
1657 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001658};
1659
Igor Murashkin545412b2017-08-17 15:26:54 -07001660class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001661 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001662 WriteCodeMethodVisitor(OatWriter* writer,
1663 OutputStream* out,
1664 const size_t file_offset,
1665 size_t relative_offset,
1666 OrderedMethodList ordered_methods)
1667 : OrderedMethodVisitor(std::move(ordered_methods)),
1668 writer_(writer),
1669 offset_(relative_offset),
1670 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001671 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1672 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1673 out_(out),
1674 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001675 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001676 dex_cache_(nullptr),
1677 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001678 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001679 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001680 // If we're creating the image, the address space must be ready so that we can apply patches.
1681 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001682 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001683 }
1684
Igor Murashkin545412b2017-08-17 15:26:54 -07001685 virtual bool VisitStart() OVERRIDE {
1686 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001687 }
1688
Igor Murashkin545412b2017-08-17 15:26:54 -07001689 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001690 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001691 dex_file_ = dex_file;
1692
1693 // Ordered method visiting is only for compiled methods.
1694 DCHECK(writer_->MayHaveCompiledMethods());
1695
Mathieu Chartier72041a02017-07-14 18:23:25 -07001696 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1697 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1698 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1699 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1700 DCHECK(dex_cache_ != nullptr);
1701 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001702 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001703 }
1704
1705 virtual bool VisitComplete() {
1706 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1707 if (UNLIKELY(offset_ == 0u)) {
1708 PLOG(ERROR) << "Failed to write final relative call thunks";
1709 return false;
1710 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001711 return true;
1712 }
1713
Igor Murashkin545412b2017-08-17 15:26:54 -07001714 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001715 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001716 const MethodReference& method_ref = method_data.method_reference;
1717 UpdateDexFileAndDexCache(method_ref.dex_file);
1718
1719 OatClass* oat_class = method_data.oat_class;
1720 CompiledMethod* compiled_method = method_data.compiled_method;
1721 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001722
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001723 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001724 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001725 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001726
Igor Murashkin545412b2017-08-17 15:26:54 -07001727 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1728 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1729 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001730
Igor Murashkin545412b2017-08-17 15:26:54 -07001731 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1732 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1733
1734 // Deduplicate code arrays.
1735 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1736 if (method_offsets.code_offset_ > offset_) {
1737 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1738 if (offset_ == 0u) {
1739 ReportWriteFailure("relative call thunk", method_ref);
1740 return false;
1741 }
1742 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1743 if (alignment_size != 0) {
1744 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1745 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001746 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001747 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001748 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001749 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001750 }
1751 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1752 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1753 DCHECK_EQ(method_offsets.code_offset_,
1754 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1755 << dex_file_->PrettyMethod(method_ref.index);
1756 const OatQuickMethodHeader& method_header =
1757 oat_class->method_headers_[method_offsets_index];
1758 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1759 ReportWriteFailure("method header", method_ref);
1760 return false;
1761 }
1762 writer_->size_method_header_ += sizeof(method_header);
1763 offset_ += sizeof(method_header);
1764 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001765
Igor Murashkin545412b2017-08-17 15:26:54 -07001766 if (!compiled_method->GetPatches().empty()) {
1767 patched_code_.assign(quick_code.begin(), quick_code.end());
1768 quick_code = ArrayRef<const uint8_t>(patched_code_);
1769 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1770 uint32_t literal_offset = patch.LiteralOffset();
1771 switch (patch.GetType()) {
1772 case LinkerPatch::Type::kMethodBssEntry: {
1773 uint32_t target_offset =
1774 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1775 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1776 patch,
1777 offset_ + literal_offset,
1778 target_offset);
1779 break;
1780 }
1781 case LinkerPatch::Type::kCallRelative: {
1782 // NOTE: Relative calls across oat files are not supported.
1783 uint32_t target_offset = GetTargetOffset(patch);
1784 writer_->relative_patcher_->PatchCall(&patched_code_,
1785 literal_offset,
1786 offset_ + literal_offset,
1787 target_offset);
1788 break;
1789 }
1790 case LinkerPatch::Type::kStringRelative: {
1791 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1792 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1793 patch,
1794 offset_ + literal_offset,
1795 target_offset);
1796 break;
1797 }
1798 case LinkerPatch::Type::kStringInternTable: {
1799 uint32_t target_offset = GetInternTableEntryOffset(patch);
1800 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1801 patch,
1802 offset_ + literal_offset,
1803 target_offset);
1804 break;
1805 }
1806 case LinkerPatch::Type::kStringBssEntry: {
1807 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1808 uint32_t target_offset =
1809 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1810 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1811 patch,
1812 offset_ + literal_offset,
1813 target_offset);
1814 break;
1815 }
1816 case LinkerPatch::Type::kTypeRelative: {
1817 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1818 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1819 patch,
1820 offset_ + literal_offset,
1821 target_offset);
1822 break;
1823 }
1824 case LinkerPatch::Type::kTypeClassTable: {
1825 uint32_t target_offset = GetClassTableEntryOffset(patch);
1826 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1827 patch,
1828 offset_ + literal_offset,
1829 target_offset);
1830 break;
1831 }
1832 case LinkerPatch::Type::kTypeBssEntry: {
1833 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1834 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1835 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1836 patch,
1837 offset_ + literal_offset,
1838 target_offset);
1839 break;
1840 }
1841 case LinkerPatch::Type::kCall: {
1842 uint32_t target_offset = GetTargetOffset(patch);
1843 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1844 break;
1845 }
1846 case LinkerPatch::Type::kMethodRelative: {
1847 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1848 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1849 patch,
1850 offset_ + literal_offset,
1851 target_offset);
1852 break;
1853 }
1854 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1855 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1856 patch,
1857 offset_ + literal_offset);
1858 break;
1859 }
1860 default: {
1861 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1862 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001863 }
1864 }
1865 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001866 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001867
1868 if (!out->WriteFully(quick_code.data(), code_size)) {
1869 ReportWriteFailure("method code", method_ref);
1870 return false;
1871 }
1872 writer_->size_code_ += code_size;
1873 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001874 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001875 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001876
1877 return true;
1878 }
1879
Igor Murashkin545412b2017-08-17 15:26:54 -07001880 size_t GetOffset() const {
1881 return offset_;
1882 }
1883
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001884 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001885 OatWriter* const writer_;
1886
1887 // Updated in VisitMethod as methods are written out.
1888 size_t offset_;
1889
1890 // Potentially varies with every different VisitMethod.
1891 // Used to determine which DexCache to use when finding ArtMethods.
1892 const DexFile* dex_file_;
1893
1894 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001895 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001896 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001897 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001898 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001899 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001900 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001901 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001902 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001903 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001904 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001905
Igor Murashkin545412b2017-08-17 15:26:54 -07001906 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001907 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001908 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001909 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001910
Mathieu Chartiere401d142015-04-22 13:56:20 -07001911 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001912 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001913 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001914 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001915 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1916 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001917 ArtMethod* method =
1918 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001919 CHECK(method != nullptr);
1920 return method;
1921 }
1922
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001923 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001924 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1925 // If there's no new compiled code, either we're compiling an app and the target method
1926 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001927 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001928 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001929 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001930 const void* oat_code_offset =
1931 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001932 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001933 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001934 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1935 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1936 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1937 target_offset = PointerToLowMemUInt32(oat_code_offset);
1938 } else {
1939 target_offset = target->IsNative()
1940 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1941 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1942 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001943 }
1944 return target_offset;
1945 }
1946
Vladimir Markocd556b02017-02-03 11:47:34 +00001947 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001948 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001949 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001950 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001951 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1952 }
1953
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001954 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001955 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001956 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001957 ObjPtr<mirror::Class> type =
1958 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001959 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001960 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001961 }
1962
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001963 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001964 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001965 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1966 patch.TargetStringIndex(),
Vladimir Markof25cc732017-03-16 16:18:15 +00001967 GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001968 DCHECK(string != nullptr);
1969 DCHECK(writer_->HasBootImage() ||
1970 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1971 return string;
1972 }
1973
Vladimir Marko65979462017-05-19 17:25:12 +01001974 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1975 DCHECK(writer_->HasBootImage());
1976 method = writer_->image_writer_->GetImageMethodAddress(method);
1977 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1978 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1979 // TODO: Clean up offset types. The target offset must be treated as signed.
1980 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1981 }
1982
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001983 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001984 DCHECK(writer_->HasBootImage());
1985 object = writer_->image_writer_->GetImageAddress(object);
1986 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1987 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1988 // TODO: Clean up offset types. The target offset must be treated as signed.
1989 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1990 }
1991
Vladimir Markof4da6752014-08-01 19:04:18 +01001992 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001993 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001994 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001995 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001996 } else {
1997 // NOTE: We're using linker patches for app->boot references when the image can
1998 // be relocated and therefore we need to emit .oat_patches. We're not using this
1999 // for app->app references, so check that the object is in the image space.
2000 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01002001 }
Vladimir Marko09d09432015-09-08 13:47:48 +01002002 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01002003 uint32_t address = PointerToLowMemUInt32(object);
2004 DCHECK_LE(offset + 4, code->size());
2005 uint8_t* data = &(*code)[offset];
2006 data[0] = address & 0xffu;
2007 data[1] = (address >> 8) & 0xffu;
2008 data[2] = (address >> 16) & 0xffu;
2009 data[3] = (address >> 24) & 0xffu;
2010 }
2011
2012 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002013 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01002014 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002015 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002016 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
2017 // TODO: Clean up offset types.
2018 // The target_offset must be treated as signed for cross-oat patching.
2019 const void* target = reinterpret_cast<const void*>(
2020 writer_->image_writer_->GetOatDataBegin(oat_index) +
2021 static_cast<int32_t>(target_offset));
2022 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01002023 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002024 DCHECK_LE(offset + 4, code->size());
2025 uint8_t* data = &(*code)[offset];
2026 data[0] = address & 0xffu;
2027 data[1] = (address >> 8) & 0xffu;
2028 data[2] = (address >> 16) & 0xffu;
2029 data[3] = (address >> 24) & 0xffu;
2030 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002031
2032 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
2033 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
2034 REQUIRES_SHARED(Locks::mutator_lock_) {
2035 DCHECK(!writer_->HasBootImage());
2036 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
2037 *patch.TargetStringDexFile(), patch.TargetStringIndex());
2038 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002039 return GetBootImageTableEntryOffset(string_root);
2040 }
2041
2042 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
2043 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
2044 REQUIRES_SHARED(Locks::mutator_lock_) {
2045 DCHECK(!writer_->HasBootImage());
2046 const uint8_t* table_slot =
2047 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
2048 DCHECK(table_slot != nullptr);
2049 return GetBootImageTableEntryOffset(table_slot);
2050 }
2051
2052 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002053 uint32_t base_offset = writer_->bss_start_;
2054 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2055 const uint8_t* const_tables_begin =
2056 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002057 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002058 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
2059 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
2060 return base_offset + offset;
2061 }
2062 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
2063 }
2064 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
2065 UNREACHABLE();
2066 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002067};
2068
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002069class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2070 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002071 WriteMapMethodVisitor(OatWriter* writer,
2072 OutputStream* out,
2073 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002074 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002075 : OatDexMethodVisitor(writer, relative_offset),
2076 out_(out),
2077 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002078
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002079 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002080 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002081 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2082
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002083 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002084 size_t file_offset = file_offset_;
2085 OutputStream* out = out_;
2086
Mingyao Yang063fc772016-08-02 11:02:54 -07002087 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002088 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002089 ++method_offsets_index_;
2090
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002091 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2092 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2093 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002094 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002095
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002096 // If vdex is enabled, only emit the map for compiled code. The quickening info
2097 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002098 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002099 // Transform map_offset to actual oat data offset.
2100 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2101 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002102 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002103
2104 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2105 size_t map_size = map.size() * sizeof(map[0]);
2106 if (map_offset == offset_) {
2107 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002108 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002109 ReportWriteFailure(it);
2110 return false;
2111 }
2112 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002113 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002114 }
2115 DCHECK_OFFSET_();
2116 }
2117
2118 return true;
2119 }
2120
2121 private:
2122 OutputStream* const out_;
2123 size_t const file_offset_;
2124
2125 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002126 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002127 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002128 }
2129};
2130
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002131class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2132 public:
2133 WriteMethodInfoVisitor(OatWriter* writer,
2134 OutputStream* out,
2135 const size_t file_offset,
2136 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002137 : OatDexMethodVisitor(writer, relative_offset),
2138 out_(out),
2139 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002140
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002141 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002142 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2143 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2144
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002145 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002146 size_t file_offset = file_offset_;
2147 OutputStream* out = out_;
2148 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2149 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2150 ++method_offsets_index_;
2151 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2152 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2153 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2154 << dex_file_->PrettyMethod(it.GetMemberIndex());
2155 if (map_offset != 0u) {
2156 // Transform map_offset to actual oat data offset.
2157 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2158 DCHECK_NE(map_offset, 0u);
2159 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2160
2161 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2162 size_t map_size = map.size() * sizeof(map[0]);
2163 if (map_offset == offset_) {
2164 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2165 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2166 ReportWriteFailure(it);
2167 return false;
2168 }
2169 offset_ += map_size;
2170 }
2171 }
2172 DCHECK_OFFSET_();
2173 }
2174
2175 return true;
2176 }
2177
2178 private:
2179 OutputStream* const out_;
2180 size_t const file_offset_;
2181
2182 void ReportWriteFailure(const ClassDataItemIterator& it) {
2183 PLOG(ERROR) << "Failed to write map for "
2184 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2185 }
2186};
2187
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002188// Visit all methods from all classes in all dex files with the specified visitor.
2189bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2190 for (const DexFile* dex_file : *dex_files_) {
2191 const size_t class_def_count = dex_file->NumClassDefs();
2192 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2193 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2194 return false;
2195 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002196 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002197 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2198 const uint8_t* class_data = dex_file->GetClassData(class_def);
2199 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2200 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002201 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002202 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002203 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002204 if (!visitor->VisitMethod(class_def_method_index, it)) {
2205 return false;
2206 }
2207 ++class_def_method_index;
2208 it.Next();
2209 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002210 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002211 }
2212 }
2213 if (UNLIKELY(!visitor->EndClass())) {
2214 return false;
2215 }
2216 }
2217 }
2218 return true;
2219}
2220
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002221size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2222 const InstructionSetFeatures* instruction_set_features,
2223 uint32_t num_dex_files,
2224 SafeMap<std::string, std::string>* key_value_store) {
2225 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2226 oat_header_.reset(OatHeader::Create(instruction_set,
2227 instruction_set_features,
2228 num_dex_files,
2229 key_value_store));
2230 size_oat_header_ += sizeof(OatHeader);
2231 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002232 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002233}
2234
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002235size_t OatWriter::InitClassOffsets(size_t offset) {
2236 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002237 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002238 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2239 if (!oat_dex_file.class_offsets_.empty()) {
2240 // Class offsets are required to be 4 byte aligned.
2241 offset = RoundUp(offset, 4u);
2242 oat_dex_file.class_offsets_offset_ = offset;
2243 offset += oat_dex_file.GetClassOffsetsRawSize();
2244 DCHECK_ALIGNED(offset, 4u);
2245 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002246 }
2247 return offset;
2248}
2249
Brian Carlstrom389efb02012-01-11 12:06:26 -08002250size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002251 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002252 InitOatClassesMethodVisitor visitor(this, offset);
2253 bool success = VisitDexMethods(&visitor);
2254 CHECK(success);
2255 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002256
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002257 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002258 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002259 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2260 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002261 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002262 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002263 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002264 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002265 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002266 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002267
2268 return offset;
2269}
2270
2271size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002272 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002273 return offset;
2274 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002275 {
2276 InitMapMethodVisitor visitor(this, offset);
2277 bool success = VisitDexMethods(&visitor);
2278 DCHECK(success);
2279 offset = visitor.GetOffset();
2280 }
2281 {
2282 InitMethodInfoVisitor visitor(this, offset);
2283 bool success = VisitDexMethods(&visitor);
2284 DCHECK(success);
2285 offset = visitor.GetOffset();
2286 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002287 return offset;
2288}
2289
Vladimir Markof3c52b42017-11-17 17:32:12 +00002290template <typename GetBssOffset>
2291static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2292 size_t slot_size,
2293 const BitVector& indexes,
2294 GetBssOffset get_bss_offset) {
2295 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2296 size_t number_of_entries = 0u;
2297 bool first_index = true;
2298 for (uint32_t index : indexes.Indexes()) {
2299 uint32_t bss_offset = get_bss_offset(index);
2300 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2301 encoder.Reset(index, bss_offset);
2302 ++number_of_entries;
2303 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002304 }
2305 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002306 DCHECK_NE(number_of_entries, 0u);
2307 return number_of_entries;
2308}
2309
2310template <typename GetBssOffset>
2311static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2312 size_t slot_size,
2313 const BitVector& indexes,
2314 GetBssOffset get_bss_offset) {
2315 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2316 slot_size,
2317 indexes,
2318 get_bss_offset);
2319 return IndexBssMapping::ComputeSize(number_of_entries);
2320}
2321
2322size_t OatWriter::InitIndexBssMappings(size_t offset) {
2323 if (bss_method_entry_references_.empty() &&
2324 bss_type_entry_references_.empty() &&
2325 bss_string_entry_references_.empty()) {
2326 return offset;
2327 }
2328 // If there are any classes, the class offsets allocation aligns the offset
2329 // and we cannot have any index bss mappings without class offsets.
2330 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2331 DCHECK_ALIGNED(offset, 4u);
2332
2333 size_t number_of_method_dex_files = 0u;
2334 size_t number_of_type_dex_files = 0u;
2335 size_t number_of_string_dex_files = 0u;
2336 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2337 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2338 const DexFile* dex_file = (*dex_files_)[i];
2339 auto method_it = bss_method_entry_references_.find(dex_file);
2340 if (method_it != bss_method_entry_references_.end()) {
2341 const BitVector& method_indexes = method_it->second;
2342 ++number_of_method_dex_files;
2343 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2344 offset += CalculateIndexBssMappingSize(
2345 dex_file->NumMethodIds(),
2346 static_cast<size_t>(pointer_size),
2347 method_indexes,
2348 [=](uint32_t index) {
2349 return bss_method_entries_.Get({dex_file, index});
2350 });
2351 }
2352
2353 auto type_it = bss_type_entry_references_.find(dex_file);
2354 if (type_it != bss_type_entry_references_.end()) {
2355 const BitVector& type_indexes = type_it->second;
2356 ++number_of_type_dex_files;
2357 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2358 offset += CalculateIndexBssMappingSize(
2359 dex_file->NumTypeIds(),
2360 sizeof(GcRoot<mirror::Class>),
2361 type_indexes,
2362 [=](uint32_t index) {
2363 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2364 });
2365 }
2366
2367 auto string_it = bss_string_entry_references_.find(dex_file);
2368 if (string_it != bss_string_entry_references_.end()) {
2369 const BitVector& string_indexes = string_it->second;
2370 ++number_of_string_dex_files;
2371 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2372 offset += CalculateIndexBssMappingSize(
2373 dex_file->NumStringIds(),
2374 sizeof(GcRoot<mirror::String>),
2375 string_indexes,
2376 [=](uint32_t index) {
2377 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2378 });
2379 }
2380 }
2381 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2382 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2383 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2384 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002385 return offset;
2386}
2387
2388size_t OatWriter::InitOatDexFiles(size_t offset) {
2389 // Initialize offsets of oat dex files.
2390 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2391 oat_dex_file.offset_ = offset;
2392 offset += oat_dex_file.SizeOf();
2393 }
2394 return offset;
2395}
2396
Brian Carlstrome24fa612011-09-29 00:53:55 -07002397size_t OatWriter::InitOatCode(size_t offset) {
2398 // calculate the offsets within OatHeader to executable code
2399 size_t old_offset = offset;
2400 // required to be on a new page boundary
2401 offset = RoundUp(offset, kPageSize);
2402 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002403 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002404 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2405 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2406 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002407 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002408 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002409 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2410 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002411
Vladimir Marko1b404a82017-09-01 13:35:26 +01002412 #define DO_TRAMPOLINE(field, fn_name) \
2413 offset = CompiledCode::AlignCode(offset, instruction_set); \
2414 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2415 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2416 (field) = compiler_driver_->Create ## fn_name(); \
2417 if (generate_debug_info) { \
2418 debug::MethodDebugInfo info = {}; \
2419 info.trampoline_name = #fn_name; \
2420 info.isa = instruction_set; \
2421 info.is_code_address_text_relative = true; \
2422 /* Use the code offset rather than the `adjusted_offset`. */ \
2423 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2424 info.code_size = (field)->size(); \
2425 method_info_.push_back(std::move(info)); \
2426 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002427 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002428
Ian Rogers848871b2013-08-05 10:56:33 -07002429 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002430 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002431 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002432 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2433 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002434
Ian Rogers848871b2013-08-05 10:56:33 -07002435 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002436 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002437 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002438 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002439 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002440 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002441 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002442 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002443 return offset;
2444}
2445
2446size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002447 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002448 if (kOatWriterDebugOatCodeLayout) {
2449 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2450 << this << "), "
2451 << "compilation is disabled";
2452 }
2453
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002454 return offset;
2455 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002456 bool success = false;
2457
2458 {
2459 ScopedObjectAccess soa(Thread::Current());
2460
2461 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2462 success = VisitDexMethods(&layout_code_visitor);
2463 DCHECK(success);
2464
2465 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2466 this,
2467 offset,
2468 layout_code_visitor.ReleaseOrderedMethods());
2469 success = layout_reserve_code_visitor.Visit();
2470 DCHECK(success);
2471 offset = layout_reserve_code_visitor.GetOffset();
2472
2473 // Save the method order because the WriteCodeMethodVisitor will need this
2474 // order again.
2475 DCHECK(ordered_methods_ == nullptr);
2476 ordered_methods_.reset(
2477 new OrderedMethodList(
2478 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2479
2480 if (kOatWriterDebugOatCodeLayout) {
2481 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2482 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2483 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2484 LOG(INFO) << pretty_name
2485 << "@ offset "
2486 << relative_patcher_->GetOffset(ordered_method.method_reference)
2487 << " X hotness "
2488 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2489 }
2490 }
2491 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002492
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002493 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002494 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002495 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002496 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002497 DCHECK(success);
2498 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002499 }
Logan Chien8b977d32012-02-21 19:14:55 +08002500
Brian Carlstrome24fa612011-09-29 00:53:55 -07002501 return offset;
2502}
2503
Vladimir Markoaad75c62016-10-03 08:46:48 +00002504void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002505 {
2506 InitBssLayoutMethodVisitor visitor(this);
2507 bool success = VisitDexMethods(&visitor);
2508 DCHECK(success);
2509 }
2510
2511 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002512 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002513 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002514 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002515 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002516 if (!map_boot_image_tables_to_bss_ &&
2517 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002518 bss_type_entries_.empty() &&
2519 bss_string_entries_.empty()) {
2520 // Nothing to put to the .bss section.
2521 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002522 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002523
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002524 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002525 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002526 if (map_boot_image_tables_to_bss_) {
2527 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2528 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2529 }
2530 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002531
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002532 bss_methods_offset_ = bss_size_;
2533
2534 // Prepare offsets for .bss ArtMethod entries.
2535 for (auto& entry : bss_method_entries_) {
2536 DCHECK_EQ(entry.second, 0u);
2537 entry.second = bss_size_;
2538 bss_size_ += static_cast<size_t>(pointer_size);
2539 }
2540
Vladimir Markoaad75c62016-10-03 08:46:48 +00002541 bss_roots_offset_ = bss_size_;
2542
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002543 // Prepare offsets for .bss Class entries.
2544 for (auto& entry : bss_type_entries_) {
2545 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002546 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002547 bss_size_ += sizeof(GcRoot<mirror::Class>);
2548 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002549 // Prepare offsets for .bss String entries.
2550 for (auto& entry : bss_string_entries_) {
2551 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002552 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002553 bss_size_ += sizeof(GcRoot<mirror::String>);
2554 }
2555}
2556
David Srbeckybc90fd02015-04-22 19:40:27 +01002557bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002558 CHECK(write_state_ == WriteState::kWriteRoData);
2559
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002560 size_t file_offset = oat_data_offset_;
2561 off_t current_offset = out->Seek(0, kSeekCurrent);
2562 if (current_offset == static_cast<off_t>(-1)) {
2563 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2564 }
2565 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2566 size_t relative_offset = current_offset - file_offset;
2567
Vladimir Markoe079e212016-05-25 12:49:49 +01002568 // Wrap out to update checksum with each write.
2569 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2570 out = &checksum_updating_out;
2571
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002572 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2573 if (relative_offset == 0) {
2574 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002575 return false;
2576 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002577
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002578 relative_offset = WriteClasses(out, file_offset, relative_offset);
2579 if (relative_offset == 0) {
2580 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002581 return false;
2582 }
2583
Vladimir Markof3c52b42017-11-17 17:32:12 +00002584 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002585 if (relative_offset == 0) {
2586 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002587 return false;
2588 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002589
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002590 relative_offset = WriteMaps(out, file_offset, relative_offset);
2591 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002592 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2593 return false;
2594 }
2595
2596 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2597 if (relative_offset == 0) {
2598 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002599 return false;
2600 }
2601
David Srbeckybc90fd02015-04-22 19:40:27 +01002602 // Write padding.
2603 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2604 relative_offset += size_executable_offset_alignment_;
2605 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2606 size_t expected_file_offset = file_offset + relative_offset;
2607 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2608 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2609 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2610 return 0;
2611 }
2612 DCHECK_OFFSET();
2613
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002614 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002615 return true;
2616}
2617
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002618class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
2619 public:
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002620 WriteQuickeningInfoMethodVisitor(OatWriter* writer,
2621 OutputStream* out,
2622 uint32_t offset,
2623 SafeMap<const uint8_t*, uint32_t>* offset_map)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002624 : DexMethodVisitor(writer, offset),
2625 out_(out),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002626 written_bytes_(0u),
2627 offset_map_(offset_map) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002628
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002629 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it)
2630 OVERRIDE {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002631 uint32_t method_idx = it.GetMemberIndex();
2632 CompiledMethod* compiled_method =
2633 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
2634
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002635 if (HasQuickeningInfo(compiled_method)) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002636 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002637 // Deduplication is already done on a pointer basis by the compiler driver,
2638 // so we can simply compare the pointers to find out if things are duplicated.
2639 if (offset_map_->find(map.data()) == offset_map_->end()) {
2640 uint32_t length = map.size() * sizeof(map.front());
2641 offset_map_->Put(map.data(), written_bytes_);
2642 if (!out_->WriteFully(&length, sizeof(length)) ||
2643 !out_->WriteFully(map.data(), length)) {
2644 PLOG(ERROR) << "Failed to write quickening info for "
2645 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to "
2646 << out_->GetLocation();
2647 return false;
2648 }
2649 written_bytes_ += sizeof(length) + length;
2650 offset_ += sizeof(length) + length;
2651 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002652 }
2653
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002654 return true;
2655 }
2656
2657 size_t GetNumberOfWrittenBytes() const {
2658 return written_bytes_;
2659 }
2660
2661 private:
2662 OutputStream* const out_;
2663 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002664 // Maps quickening map to its offset in the file.
2665 SafeMap<const uint8_t*, uint32_t>* offset_map_;
2666};
2667
2668class OatWriter::WriteQuickeningIndicesMethodVisitor {
2669 public:
2670 WriteQuickeningIndicesMethodVisitor(OutputStream* out,
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002671 uint32_t quickening_info_bytes,
2672 const SafeMap<const uint8_t*, uint32_t>& offset_map)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002673 : out_(out),
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002674 quickening_info_bytes_(quickening_info_bytes),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002675 written_bytes_(0u),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002676 offset_map_(offset_map) {}
2677
2678 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files, const CompilerDriver& driver) {
2679 for (const DexFile* dex_file : dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002680 const size_t class_def_count = dex_file->NumClassDefs();
2681 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2682 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2683 const uint8_t* class_data = dex_file->GetClassData(class_def);
2684 if (class_data == nullptr) {
2685 continue;
2686 }
2687 for (ClassDataItemIterator class_it(*dex_file, class_data);
2688 class_it.HasNext();
2689 class_it.Next()) {
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002690 if (!class_it.IsAtMethod() || class_it.GetMethodCodeItem() == nullptr) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002691 continue;
2692 }
2693 uint32_t method_idx = class_it.GetMemberIndex();
2694 CompiledMethod* compiled_method =
2695 driver.GetCompiledMethod(MethodReference(dex_file, method_idx));
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002696 const DexFile::CodeItem* code_item = class_it.GetMethodCodeItem();
2697 uint32_t existing_debug_info_offset = OatFile::GetDebugInfoOffset(*dex_file, code_item);
2698 // If the existing offset is already out of bounds (and not magic marker 0xFFFFFFFF)
2699 // we will pretend the method has been quickened.
2700 bool existing_offset_out_of_bounds =
2701 (existing_debug_info_offset >= dex_file->Size() &&
2702 existing_debug_info_offset != 0xFFFFFFFF);
2703 bool has_quickening_info = HasQuickeningInfo(compiled_method);
2704 if (has_quickening_info || existing_offset_out_of_bounds) {
2705 uint32_t new_debug_info_offset =
2706 dex_file->Size() + quickening_info_bytes_ + written_bytes_;
2707 // Abort if overflow.
2708 CHECK_GE(new_debug_info_offset, dex_file->Size());
2709 const_cast<DexFile::CodeItem*>(code_item)->SetDebugInfoOffset(new_debug_info_offset);
2710 uint32_t quickening_offset = has_quickening_info
2711 ? offset_map_.Get(compiled_method->GetVmapTable().data())
2712 : VdexFile::kNoQuickeningInfoOffset;
2713 if (!out_->WriteFully(&existing_debug_info_offset,
2714 sizeof(existing_debug_info_offset)) ||
2715 !out_->WriteFully(&quickening_offset, sizeof(quickening_offset))) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002716 PLOG(ERROR) << "Failed to write quickening info for "
2717 << dex_file->PrettyMethod(method_idx) << " to "
2718 << out_->GetLocation();
2719 return false;
2720 }
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002721 written_bytes_ += sizeof(existing_debug_info_offset) + sizeof(quickening_offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002722 }
2723 }
2724 }
2725 }
2726 return true;
2727 }
2728
2729 size_t GetNumberOfWrittenBytes() const {
2730 return written_bytes_;
2731 }
2732
2733 private:
2734 OutputStream* const out_;
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002735 const uint32_t quickening_info_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002736 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002737 // Maps quickening map to its offset in the file.
2738 const SafeMap<const uint8_t*, uint32_t>& offset_map_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002739};
2740
2741bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002742 size_t initial_offset = vdex_size_;
2743 size_t start_offset = RoundUp(initial_offset, 4u);
2744
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002745 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2746 if (actual_offset != static_cast<off_t>(start_offset)) {
2747 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2748 << " Expected: " << start_offset
2749 << " Output: " << vdex_out->GetLocation();
2750 return false;
2751 }
2752
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002753 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002754 std::vector<uint32_t> dex_files_indices;
2755 SafeMap<const uint8_t*, uint32_t> offset_map;
2756 WriteQuickeningInfoMethodVisitor visitor1(this, vdex_out, start_offset, &offset_map);
2757 if (!VisitDexMethods(&visitor1)) {
2758 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2759 return false;
2760 }
2761
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002762 if (visitor1.GetNumberOfWrittenBytes() > 0) {
2763 WriteQuickeningIndicesMethodVisitor visitor2(vdex_out,
2764 visitor1.GetNumberOfWrittenBytes(),
2765 offset_map);
2766 if (!visitor2.VisitDexMethods(*dex_files_, *compiler_driver_)) {
2767 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2768 << vdex_out->GetLocation();
2769 return false;
2770 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002771
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002772 if (!vdex_out->Flush()) {
2773 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2774 << " File: " << vdex_out->GetLocation();
2775 return false;
2776 }
2777 size_quickening_info_ = visitor1.GetNumberOfWrittenBytes() +
2778 visitor2.GetNumberOfWrittenBytes();
2779 } else {
2780 // We know we did not quicken.
2781 size_quickening_info_ = 0;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002782 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002783 } else {
2784 // We know we did not quicken.
2785 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002786 }
2787
David Brazdil93592f52017-12-08 10:53:27 +00002788 if (size_quickening_info_ == 0) {
2789 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2790 vdex_quickening_info_offset_ = initial_offset;
2791 size_quickening_info_alignment_ = 0;
2792 } else {
2793 vdex_size_ = start_offset + size_quickening_info_;
2794 vdex_quickening_info_offset_ = start_offset;
2795 size_quickening_info_alignment_ = start_offset - initial_offset;
2796 }
2797
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002798 return true;
2799}
2800
David Brazdil5d5a36b2016-09-14 15:34:10 +01002801bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002802 if (verifier_deps == nullptr) {
2803 // Nothing to write. Record the offset, but no need
2804 // for alignment.
2805 vdex_verifier_deps_offset_ = vdex_size_;
2806 return true;
2807 }
2808
2809 size_t initial_offset = vdex_size_;
2810 size_t start_offset = RoundUp(initial_offset, 4u);
2811
2812 vdex_size_ = start_offset;
2813 vdex_verifier_deps_offset_ = vdex_size_;
2814 size_verifier_deps_alignment_ = start_offset - initial_offset;
2815
2816 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2817 if (actual_offset != static_cast<off_t>(start_offset)) {
2818 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2819 << " Expected: " << start_offset
2820 << " Output: " << vdex_out->GetLocation();
2821 return false;
2822 }
2823
2824 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002825 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002826
2827 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2828 PLOG(ERROR) << "Failed to write verifier deps."
2829 << " File: " << vdex_out->GetLocation();
2830 return false;
2831 }
2832 if (!vdex_out->Flush()) {
2833 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2834 << " File: " << vdex_out->GetLocation();
2835 return false;
2836 }
2837
2838 size_verifier_deps_ = buffer.size();
2839 vdex_size_ += size_verifier_deps_;
2840 return true;
2841}
2842
David Srbeckybc90fd02015-04-22 19:40:27 +01002843bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002844 CHECK(write_state_ == WriteState::kWriteText);
2845
Vladimir Markoe079e212016-05-25 12:49:49 +01002846 // Wrap out to update checksum with each write.
2847 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2848 out = &checksum_updating_out;
2849
Vladimir Marko944da602016-02-19 12:27:55 +00002850 SetMultiOatRelativePatcherAdjustment();
2851
David Srbeckybc90fd02015-04-22 19:40:27 +01002852 const size_t file_offset = oat_data_offset_;
2853 size_t relative_offset = oat_header_->GetExecutableOffset();
2854 DCHECK_OFFSET();
2855
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002856 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002857 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002858 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002859 return false;
2860 }
2861
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002862 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2863 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002864 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002865 return false;
2866 }
2867
Vladimir Markof4da6752014-08-01 19:04:18 +01002868 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002869 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002870 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2871 return false;
2872 }
2873
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002874 if (kIsDebugBuild) {
2875 uint32_t size_total = 0;
2876 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002877 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2878 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002879
David Brazdil7b49e6c2016-09-01 11:06:18 +01002880 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002881 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002882 DO_STAT(size_dex_file_alignment_);
2883 DO_STAT(size_executable_offset_alignment_);
2884 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002885 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002886 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002887 DO_STAT(size_verifier_deps_);
2888 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002889 DO_STAT(size_quickening_info_);
2890 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002891 DO_STAT(size_interpreter_to_interpreter_bridge_);
2892 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2893 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002894 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002895 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002896 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002897 DO_STAT(size_quick_to_interpreter_bridge_);
2898 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002899 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002900 DO_STAT(size_code_);
2901 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002902 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002903 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002904 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002905 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002906 DO_STAT(size_oat_dex_file_location_size_);
2907 DO_STAT(size_oat_dex_file_location_data_);
2908 DO_STAT(size_oat_dex_file_location_checksum_);
2909 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002910 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002911 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002912 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2913 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2914 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002915 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002916 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2917 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002918 DO_STAT(size_oat_lookup_table_alignment_);
2919 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002920 DO_STAT(size_oat_class_offsets_alignment_);
2921 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002922 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002923 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002924 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002925 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002926 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002927 DO_STAT(size_type_bss_mappings_);
2928 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002929 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002930
David Brazdil7b49e6c2016-09-01 11:06:18 +01002931 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2932
2933 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2934 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002935 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002936
David Brazdil7b49e6c2016-09-01 11:06:18 +01002937 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2938 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002939
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002940 write_state_ = WriteState::kWriteHeader;
2941 return true;
2942}
2943
2944bool OatWriter::WriteHeader(OutputStream* out,
2945 uint32_t image_file_location_oat_checksum,
2946 uintptr_t image_file_location_oat_begin,
2947 int32_t image_patch_delta) {
2948 CHECK(write_state_ == WriteState::kWriteHeader);
2949
2950 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2951 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002952 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002953 CHECK_EQ(image_patch_delta, 0);
2954 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2955 } else {
2956 CHECK_ALIGNED(image_patch_delta, kPageSize);
2957 oat_header_->SetImagePatchDelta(image_patch_delta);
2958 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002959 oat_header_->UpdateChecksumWithHeaderData();
2960
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002961 const size_t file_offset = oat_data_offset_;
2962
2963 off_t current_offset = out->Seek(0, kSeekCurrent);
2964 if (current_offset == static_cast<off_t>(-1)) {
2965 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2966 return false;
2967 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002968 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002969 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2970 return false;
2971 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002972 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002973
2974 // Flush all other data before writing the header.
2975 if (!out->Flush()) {
2976 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2977 return false;
2978 }
2979 // Write the header.
2980 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002981 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002982 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2983 return false;
2984 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002985 // Flush the header data.
2986 if (!out->Flush()) {
2987 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002988 return false;
2989 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002990
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002991 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2992 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2993 return false;
2994 }
2995 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2996
2997 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002998 return true;
2999}
3000
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003001size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003002 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3003 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003004 // Class offsets are required to be 4 byte aligned.
3005 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
3006 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
3007 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
3008 return 0u;
3009 }
3010 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00003011 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003012 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003013 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003014 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003015 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003016 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003017 }
3018 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003019 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003020}
3021
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003022size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003023 const bool may_have_compiled = MayHaveCompiledMethods();
3024 if (may_have_compiled) {
3025 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
3026 }
3027 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003028 // If there are any classes, the class offsets allocation aligns the offset.
3029 DCHECK_ALIGNED(relative_offset, 4u);
3030 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003031 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003032 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00003033 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003034 relative_offset += oat_class_headers_[i].SizeOf();
3035 if (may_have_compiled) {
3036 if (!oat_classes_[i].Write(this, out)) {
3037 return 0u;
3038 }
3039 relative_offset += oat_classes_[i].SizeOf();
3040 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003041 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003042 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003043}
3044
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003045size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003046 {
3047 size_t vmap_tables_offset = relative_offset;
3048 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
3049 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3050 return 0;
3051 }
3052 relative_offset = visitor.GetOffset();
3053 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003054 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003055 {
3056 size_t method_infos_offset = relative_offset;
3057 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
3058 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3059 return 0;
3060 }
3061 relative_offset = visitor.GetOffset();
3062 size_method_info_ = relative_offset - method_infos_offset;
3063 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003064
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003065 return relative_offset;
3066}
3067
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003068
Vladimir Markof3c52b42017-11-17 17:32:12 +00003069template <typename GetBssOffset>
3070size_t WriteIndexBssMapping(OutputStream* out,
3071 size_t number_of_indexes,
3072 size_t slot_size,
3073 const BitVector& indexes,
3074 GetBssOffset get_bss_offset) {
3075 // Allocate the IndexBssMapping.
3076 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
3077 number_of_indexes, slot_size, indexes, get_bss_offset);
3078 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
3079 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
3080 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
3081 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
3082 mappings->ClearPadding();
3083 // Encode the IndexBssMapping.
3084 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
3085 auto init_it = mappings->begin();
3086 bool first_index = true;
3087 for (uint32_t index : indexes.Indexes()) {
3088 size_t bss_offset = get_bss_offset(index);
3089 if (first_index) {
3090 first_index = false;
3091 encoder.Reset(index, bss_offset);
3092 } else if (!encoder.TryMerge(index, bss_offset)) {
3093 *init_it = encoder.GetEntry();
3094 ++init_it;
3095 encoder.Reset(index, bss_offset);
3096 }
3097 }
3098 // Store the last entry.
3099 *init_it = encoder.GetEntry();
3100 ++init_it;
3101 DCHECK(init_it == mappings->end());
3102
3103 if (!out->WriteFully(storage.get(), mappings_size)) {
3104 return 0u;
3105 }
3106 return mappings_size;
3107}
3108
3109size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
3110 size_t file_offset,
3111 size_t relative_offset) {
3112 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
3113 if (bss_method_entry_references_.empty() &&
3114 bss_type_entry_references_.empty() &&
3115 bss_string_entry_references_.empty()) {
3116 return relative_offset;
3117 }
3118 // If there are any classes, the class offsets allocation aligns the offset
3119 // and we cannot have method bss mappings without class offsets.
3120 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
3121 "IndexBssMapping alignment check.");
3122 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
3123
3124 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003125 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
3126 const DexFile* dex_file = (*dex_files_)[i];
3127 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00003128 auto method_it = bss_method_entry_references_.find(dex_file);
3129 if (method_it != bss_method_entry_references_.end()) {
3130 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003131 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
3132 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00003133 size_t method_mappings_size = WriteIndexBssMapping(
3134 out,
3135 dex_file->NumMethodIds(),
3136 static_cast<size_t>(pointer_size),
3137 method_indexes,
3138 [=](uint32_t index) {
3139 return bss_method_entries_.Get({dex_file, index});
3140 });
3141 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003142 return 0u;
3143 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003144 size_method_bss_mappings_ += method_mappings_size;
3145 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003146 } else {
3147 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3148 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003149
3150 auto type_it = bss_type_entry_references_.find(dex_file);
3151 if (type_it != bss_type_entry_references_.end()) {
3152 const BitVector& type_indexes = type_it->second;
3153 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3154 DCHECK_OFFSET();
3155 size_t type_mappings_size = WriteIndexBssMapping(
3156 out,
3157 dex_file->NumTypeIds(),
3158 sizeof(GcRoot<mirror::Class>),
3159 type_indexes,
3160 [=](uint32_t index) {
3161 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3162 });
3163 if (type_mappings_size == 0u) {
3164 return 0u;
3165 }
3166 size_type_bss_mappings_ += type_mappings_size;
3167 relative_offset += type_mappings_size;
3168 } else {
3169 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3170 }
3171
3172 auto string_it = bss_string_entry_references_.find(dex_file);
3173 if (string_it != bss_string_entry_references_.end()) {
3174 const BitVector& string_indexes = string_it->second;
3175 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3176 DCHECK_OFFSET();
3177 size_t string_mappings_size = WriteIndexBssMapping(
3178 out,
3179 dex_file->NumStringIds(),
3180 sizeof(GcRoot<mirror::String>),
3181 string_indexes,
3182 [=](uint32_t index) {
3183 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3184 });
3185 if (string_mappings_size == 0u) {
3186 return 0u;
3187 }
3188 size_string_bss_mappings_ += string_mappings_size;
3189 relative_offset += string_mappings_size;
3190 } else {
3191 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3192 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003193 }
3194 return relative_offset;
3195}
3196
3197size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3198 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3199
3200 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3201 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3202 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3203 DCHECK_OFFSET();
3204
3205 // Write OatDexFile.
3206 if (!oat_dex_file->Write(this, out)) {
3207 return 0u;
3208 }
3209 relative_offset += oat_dex_file->SizeOf();
3210 }
3211
3212 return relative_offset;
3213}
3214
3215size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003216 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003217 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003218
Ian Rogers848871b2013-08-05 10:56:33 -07003219 #define DO_TRAMPOLINE(field) \
3220 do { \
3221 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3222 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003223 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003224 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003225 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003226 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003227 return false; \
3228 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003229 size_ ## field += (field)->size(); \
3230 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003231 DCHECK_OFFSET(); \
3232 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003233
Ian Rogers848871b2013-08-05 10:56:33 -07003234 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003235 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003236 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003237 DO_TRAMPOLINE(quick_resolution_trampoline_);
3238 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3239 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003240 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003241 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003242}
3243
Ian Rogers3d504072014-03-01 09:16:49 -08003244size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003245 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003246 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003247 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3248 // As with InitOatCodeDexFiles, also skip the writer if
3249 // compilation was disabled.
3250 if (kOatWriterDebugOatCodeLayout) {
3251 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3252 << this << "), "
3253 << "compilation is disabled";
3254 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003255
Igor Murashkin545412b2017-08-17 15:26:54 -07003256 return relative_offset;
3257 }
3258 ScopedObjectAccess soa(Thread::Current());
3259 DCHECK(ordered_methods_ != nullptr);
3260 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3261 std::move(ordered_methods_);
3262 WriteCodeMethodVisitor visitor(this,
3263 out,
3264 file_offset,
3265 relative_offset,
3266 std::move(*ordered_methods_ptr));
3267 if (UNLIKELY(!visitor.Visit())) {
3268 return 0;
3269 }
3270 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003271
Vladimir Markob163bb72015-03-31 21:49:49 +01003272 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3273 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3274 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3275
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003276 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003277}
3278
Vladimir Marko944da602016-02-19 12:27:55 +00003279bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003280 // Get the elf file offset of the oat file.
3281 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3282 if (raw_file_offset == static_cast<off_t>(-1)) {
3283 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3284 return false;
3285 }
3286 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3287 return true;
3288}
3289
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003290bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003291 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003292
David Brazdil7b49e6c2016-09-01 11:06:18 +01003293 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003294
3295 // Write dex files.
3296 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003297 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003298 return false;
3299 }
3300 }
3301
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003302 CloseSources();
3303 return true;
3304}
3305
3306void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003307 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3308 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3309 }
3310 zipped_dex_files_.clear();
3311 zip_archives_.clear();
3312 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003313}
3314
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003315bool OatWriter::WriteDexFile(OutputStream* out,
3316 File* file,
3317 OatDexFile* oat_dex_file,
3318 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003319 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003320 return false;
3321 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003322 if (profile_compilation_info_ != nullptr ||
3323 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01003324 CHECK(!update_input_vdex) << "We should never update the input vdex when doing dexlayout";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003325 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3326 return false;
3327 }
3328 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003329 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003330 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003331 return false;
3332 }
3333 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003334 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003335 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003336 return false;
3337 }
3338 } else {
3339 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003340 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003341 return false;
3342 }
3343 }
3344
3345 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003346 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3347 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003348 size_dex_file_ += oat_dex_file->dex_file_size_;
3349 return true;
3350}
3351
3352bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3353 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003354 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003355 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003356 size_t file_offset = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003357 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003358
3359 // Seek to the start of the dex file and flush any pending operations in the stream.
3360 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003361 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3362 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003363 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003364 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003365 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3366 return false;
3367 }
3368 if (!out->Flush()) {
3369 PLOG(ERROR) << "Failed to flush before writing dex file."
3370 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3371 return false;
3372 }
3373 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003374 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003375 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003376 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003377 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3378 return false;
3379 }
3380
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003381 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003382 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003383 return true;
3384}
3385
Jeff Hao608f2ce2016-10-19 11:17:11 -07003386bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3387 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3388 std::string error_msg;
3389 std::string location(oat_dex_file->GetLocation());
3390 std::unique_ptr<const DexFile> dex_file;
3391 if (oat_dex_file->source_.IsZipEntry()) {
3392 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3393 std::unique_ptr<MemMap> mem_map(
3394 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003395 if (mem_map == nullptr) {
3396 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3397 return false;
3398 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003399 dex_file = DexFileLoader::Open(location,
3400 zip_entry->GetCrc32(),
3401 std::move(mem_map),
3402 /* verify */ true,
3403 /* verify_checksum */ true,
3404 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003405 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003406 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003407 int dup_fd = dup(raw_file->Fd());
3408 if (dup_fd < 0) {
3409 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3410 return false;
3411 }
Nicolas Geoffray095c6c92017-10-19 13:59:55 +01003412 dex_file = DexFileLoader::OpenDex(
3413 dup_fd, location, /* verify */ true, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003414 } else {
3415 // The source data is a vdex file.
3416 CHECK(oat_dex_file->source_.IsRawData())
3417 << static_cast<size_t>(oat_dex_file->source_.GetType());
3418 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3419 // Note: The raw data has already been checked to contain the header
3420 // and all the data that the header specifies as the file size.
3421 DCHECK(raw_dex_file != nullptr);
3422 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3423 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3424 // Since the source may have had its layout changed, or may be quickened, don't verify it.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003425 dex_file = DexFileLoader::Open(raw_dex_file,
3426 header->file_size_,
3427 location,
3428 oat_dex_file->dex_file_location_checksum_,
3429 nullptr,
3430 /* verify */ false,
3431 /* verify_checksum */ false,
3432 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003433 }
Jeff Haode197542017-02-03 10:48:13 -08003434 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003435 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003436 return false;
3437 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003438 Options options;
3439 options.output_to_memmap_ = true;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003440 options.compact_dex_level_ = compact_dex_level_;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003441 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
3442 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
3443 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003444 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3445 // Dex layout can affect the size of the dex file, so we update here what we have set
3446 // when adding the dex file as a source.
3447 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(mem_map->Begin());
3448 oat_dex_file->dex_file_size_ = header->file_size_;
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003449 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003450 return false;
3451 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003452 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003453 return true;
3454}
3455
David Brazdil7b49e6c2016-09-01 11:06:18 +01003456bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003457 File* file,
3458 OatDexFile* oat_dex_file,
3459 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003460 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003461 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003462
3463 // Extract the dex file and get the extracted size.
3464 std::string error_msg;
3465 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3466 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3467 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3468 return false;
3469 }
3470 if (file->Flush() != 0) {
3471 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3472 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3473 return false;
3474 }
3475 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3476 if (extracted_end == static_cast<off_t>(-1)) {
3477 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3478 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3479 return false;
3480 }
3481 if (extracted_end < static_cast<off_t>(start_offset)) {
3482 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3483 << " Start: " << start_offset
3484 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3485 return false;
3486 }
3487 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3488 if (extracted_size < sizeof(DexFile::Header)) {
3489 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3490 << extracted_size << " File: " << oat_dex_file->GetLocation();
3491 return false;
3492 }
3493
3494 // Read the dex file header and extract required data to OatDexFile.
3495 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3496 if (actual_offset != static_cast<off_t>(start_offset)) {
3497 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3498 << " Expected: " << start_offset
3499 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3500 return false;
3501 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003502 if (extracted_size < oat_dex_file->dex_file_size_) {
3503 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3504 << " file size from header: " << oat_dex_file->dex_file_size_
3505 << " File: " << oat_dex_file->GetLocation();
3506 return false;
3507 }
3508
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003509 // Seek both file and stream to the end offset.
3510 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3511 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3512 if (actual_offset != static_cast<off_t>(end_offset)) {
3513 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3514 << " Expected: " << end_offset
3515 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3516 return false;
3517 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003518 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003519 if (actual_offset != static_cast<off_t>(end_offset)) {
3520 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3521 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3522 return false;
3523 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003524 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003525 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3526 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3527 return false;
3528 }
3529
3530 // If we extracted more than the size specified in the header, truncate the file.
3531 if (extracted_size > oat_dex_file->dex_file_size_) {
3532 if (file->SetLength(end_offset) != 0) {
3533 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003534 << " File: " << oat_dex_file->GetLocation()
3535 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003536 return false;
3537 }
3538 }
3539
3540 return true;
3541}
3542
David Brazdil7b49e6c2016-09-01 11:06:18 +01003543bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003544 File* file,
3545 OatDexFile* oat_dex_file,
3546 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003547 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003548 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003549
3550 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3551 if (input_offset != static_cast<off_t>(0)) {
3552 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3553 << " Expected: 0"
3554 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3555 return false;
3556 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003557
3558 // Copy the input dex file using sendfile().
3559 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3560 PLOG(ERROR) << "Failed to copy dex file to oat file."
3561 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3562 return false;
3563 }
3564 if (file->Flush() != 0) {
3565 PLOG(ERROR) << "Failed to flush dex file."
3566 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3567 return false;
3568 }
3569
3570 // Check file position and seek the stream to the end offset.
3571 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3572 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3573 if (actual_offset != static_cast<off_t>(end_offset)) {
3574 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3575 << " Expected: " << end_offset
3576 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3577 return false;
3578 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003579 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003580 if (actual_offset != static_cast<off_t>(end_offset)) {
3581 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3582 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3583 return false;
3584 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003585 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003586 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3587 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3588 return false;
3589 }
3590
3591 return true;
3592}
3593
David Brazdil7b49e6c2016-09-01 11:06:18 +01003594bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003595 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003596 const uint8_t* dex_file,
3597 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003598 // Note: The raw data has already been checked to contain the header
3599 // and all the data that the header specifies as the file size.
3600 DCHECK(dex_file != nullptr);
3601 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3602 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3603
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003604 if (update_input_vdex) {
3605 // The vdex already contains the dex code, no need to write it again.
3606 } else {
3607 if (!out->WriteFully(dex_file, header->file_size_)) {
3608 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3609 << " to " << out->GetLocation();
3610 return false;
3611 }
3612 if (!out->Flush()) {
3613 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3614 << " File: " << oat_dex_file->GetLocation();
3615 return false;
3616 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003617 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003618 return true;
3619}
3620
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003621bool OatWriter::OpenDexFiles(
3622 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003623 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003624 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
3625 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3626 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3627
3628 if (oat_dex_files_.empty()) {
3629 // Nothing to do.
3630 return true;
3631 }
3632
3633 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003634 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003635
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003636 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003637 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3638 length,
3639 PROT_READ | PROT_WRITE,
3640 MAP_SHARED,
3641 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003642 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003643 /* low_4gb */ false,
3644 file->GetPath().c_str(),
3645 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003646 if (dex_files_map == nullptr) {
3647 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3648 << " error: " << error_msg;
3649 return false;
3650 }
3651 std::vector<std::unique_ptr<const DexFile>> dex_files;
3652 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003653 const uint8_t* raw_dex_file =
3654 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003655
3656 if (kIsDebugBuild) {
3657 // Sanity check our input files.
3658 // Note that ValidateDexFileHeader() logs error messages.
3659 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3660 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003661 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3662 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003663
3664 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3665 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3666 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003667 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3668 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003669 }
3670
3671 // Now, open the dex file.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003672 dex_files.emplace_back(DexFileLoader::Open(raw_dex_file,
3673 oat_dex_file.dex_file_size_,
3674 oat_dex_file.GetLocation(),
3675 oat_dex_file.dex_file_location_checksum_,
3676 /* oat_dex_file */ nullptr,
3677 verify,
3678 verify,
3679 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003680 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003681 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3682 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003683 return false;
3684 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003685
3686 // Set the class_offsets size now that we have easy access to the DexFile and
3687 // it has been verified in DexFileLoader::Open.
3688 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003689 }
3690
3691 *opened_dex_files_map = std::move(dex_files_map);
3692 *opened_dex_files = std::move(dex_files);
3693 return true;
3694}
3695
3696bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003697 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003698 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3699 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3700
David Brazdil7b49e6c2016-09-01 11:06:18 +01003701 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3702 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3703 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3704 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3705 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3706 return false;
3707 }
3708
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003709 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3710 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3711 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003712 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3713
3714 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3715 oat_dex_file->class_offsets_.empty()) {
3716 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003717 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003718
3719 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3720 if (table_size == 0u) {
3721 continue;
3722 }
3723
3724 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003725 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003726 const DexFile& dex_file = *opened_dex_files[i];
3727 {
3728 std::unique_ptr<TypeLookupTable> type_lookup_table =
3729 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3730 type_lookup_table_oat_dex_files_.push_back(
3731 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3732 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3733 }
3734 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003735
3736 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003737 size_t initial_offset = oat_size_;
3738 size_t rodata_offset = RoundUp(initial_offset, 4);
3739 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003740
3741 if (padding_size != 0u) {
3742 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003743 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003744 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3745 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003746 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003747 return false;
3748 }
3749 }
3750
3751 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003752 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003753 DCHECK_EQ(table_size, table->RawDataLength());
3754
David Brazdil7b49e6c2016-09-01 11:06:18 +01003755 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003756 PLOG(ERROR) << "Failed to write lookup table."
3757 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003758 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003759 return false;
3760 }
3761
3762 oat_dex_file->lookup_table_offset_ = rodata_offset;
3763
David Brazdil7b49e6c2016-09-01 11:06:18 +01003764 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003765 size_oat_lookup_table_ += table_size;
3766 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003767 }
3768
David Brazdil7b49e6c2016-09-01 11:06:18 +01003769 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003770 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003771 << " File: " << oat_rodata->GetLocation();
3772 return false;
3773 }
3774
3775 return true;
3776}
3777
Mathieu Chartier120aa282017-08-05 16:03:03 -07003778bool OatWriter::WriteDexLayoutSections(
3779 OutputStream* oat_rodata,
3780 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3781 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3782
3783 if (!kWriteDexLayoutInfo) {
3784 return true;;
3785 }
3786
3787 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3788 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3789 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3790 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3791 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3792 return false;
3793 }
3794
3795 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3796 size_t rodata_offset = oat_size_;
3797 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3798 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3799 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3800
3801 // Write dex layout section alignment bytes.
3802 const size_t padding_size =
3803 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3804 if (padding_size != 0u) {
3805 std::vector<uint8_t> buffer(padding_size, 0u);
3806 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3807 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3808 << " File: " << oat_dex_file->GetLocation()
3809 << " Output: " << oat_rodata->GetLocation();
3810 return false;
3811 }
3812 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3813 rodata_offset += padding_size;
3814 }
3815
3816 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3817 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3818 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3819 DCHECK(oat_dex_file != nullptr);
3820 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3821 sizeof(oat_dex_file->dex_sections_layout_))) {
3822 PLOG(ERROR) << "Failed to write dex layout sections."
3823 << " File: " << oat_dex_file->GetLocation()
3824 << " Output: " << oat_rodata->GetLocation();
3825 return false;
3826 }
3827 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3828 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3829 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3830 }
3831 oat_size_ = rodata_offset;
3832
3833 if (!oat_rodata->Flush()) {
3834 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3835 << " File: " << oat_rodata->GetLocation();
3836 return false;
3837 }
3838
3839 return true;
3840}
3841
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003842bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003843 // Write checksums
3844 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
3845 if (actual_offset != sizeof(VdexFile::Header)) {
3846 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3847 << " File: " << vdex_out->GetLocation();
3848 return false;
3849 }
3850
3851 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3852 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3853 if (!vdex_out->WriteFully(
3854 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3855 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3856 << vdex_out->GetLocation();
3857 return false;
3858 }
3859 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3860 }
3861
3862 // Write header.
3863 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003864 if (actual_offset != 0) {
3865 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3866 << " File: " << vdex_out->GetLocation();
3867 return false;
3868 }
3869
David Brazdil5d5a36b2016-09-14 15:34:10 +01003870 DCHECK_NE(vdex_dex_files_offset_, 0u);
3871 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
David Brazdil93592f52017-12-08 10:53:27 +00003872 DCHECK_NE(vdex_quickening_info_offset_, 0u);
David Brazdil5d5a36b2016-09-14 15:34:10 +01003873
3874 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003875 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3876 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003877
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003878 VdexFile::Header vdex_header(oat_dex_files_.size(),
3879 dex_section_size,
3880 verifier_deps_section_size,
3881 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003882 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
3883 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003884 return false;
3885 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003886 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003887
David Brazdil5d5a36b2016-09-14 15:34:10 +01003888 if (!vdex_out->Flush()) {
3889 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3890 << " File: " << vdex_out->GetLocation();
3891 return false;
3892 }
3893
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003894 return true;
3895}
3896
Vladimir Markof4da6752014-08-01 19:04:18 +01003897bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003898 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3899}
3900
3901bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003902 static const uint8_t kPadding[] = {
3903 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3904 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003905 DCHECK_LE(size, sizeof(kPadding));
3906 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003907 return false;
3908 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003909 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01003910 return true;
3911}
3912
Vladimir Marko944da602016-02-19 12:27:55 +00003913void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3914 DCHECK(dex_files_ != nullptr);
3915 DCHECK(relative_patcher_ != nullptr);
3916 DCHECK_NE(oat_data_offset_, 0u);
3917 if (image_writer_ != nullptr && !dex_files_->empty()) {
3918 // The oat data begin may not be initialized yet but the oat file offset is ready.
3919 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3920 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3921 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01003922 }
3923}
3924
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003925OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3926 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003927 CreateTypeLookupTable create_type_lookup_table,
3928 uint32_t dex_file_location_checksum,
3929 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003930 : source_(source),
3931 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003932 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003933 offset_(0),
3934 dex_file_location_size_(strlen(dex_file_location)),
3935 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003936 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003937 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00003938 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003939 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003940 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00003941 type_bss_mapping_offset_(0u),
3942 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00003943 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003944 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07003945}
3946
3947size_t OatWriter::OatDexFile::SizeOf() const {
3948 return sizeof(dex_file_location_size_)
3949 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003950 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08003951 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003952 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003953 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003954 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00003955 + sizeof(type_bss_mapping_offset_)
3956 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003957 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003958}
3959
3960bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3961 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003962 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003963
Vladimir Markoe079e212016-05-25 12:49:49 +01003964 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003965 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003966 return false;
3967 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003968 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003969
Vladimir Markoe079e212016-05-25 12:49:49 +01003970 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003971 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003972 return false;
3973 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003974 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003975
Vladimir Markoe079e212016-05-25 12:49:49 +01003976 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003977 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003978 return false;
3979 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003980 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003981
Vladimir Markoe079e212016-05-25 12:49:49 +01003982 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003983 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003984 return false;
3985 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003986 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003987
Vladimir Markoe079e212016-05-25 12:49:49 +01003988 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003989 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3990 return false;
3991 }
3992 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3993
Vladimir Markoe079e212016-05-25 12:49:49 +01003994 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003995 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3996 return false;
3997 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003998 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003999
Mathieu Chartier120aa282017-08-05 16:03:03 -07004000 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4001 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4002 return false;
4003 }
4004 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4005
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004006 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4007 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4008 return false;
4009 }
4010 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4011
Vladimir Markof3c52b42017-11-17 17:32:12 +00004012 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4013 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4014 return false;
4015 }
4016 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4017
4018 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4019 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4020 return false;
4021 }
4022 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4023
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004024 return true;
4025}
4026
4027bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004028 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004029 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4030 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004031 return false;
4032 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004033 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004034 return true;
4035}
4036
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004037OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004038 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004039 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004040 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004041 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004042 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004043
Brian Carlstromba150c32013-08-27 17:31:03 -07004044 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4045
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004046 method_offsets_.resize(compiled_methods_with_code);
4047 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004048
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004049 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4050 // We only create this instance if there are at least some compiled.
4051 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004052 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004053 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4054 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4055 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4056 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004057 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004058 method_bitmap_size_ = 0;
4059 }
4060
4061 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004062 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004063 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004064 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4065 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004066 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004067 method_bitmap_->SetBit(i);
4068 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004069 } else {
4070 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004071 }
4072 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004073}
4074
Brian Carlstrom265091e2013-01-30 14:08:26 -08004075size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004076 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004077 + method_bitmap_size_
4078 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004079}
4080
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004081bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4082 OutputStream* out,
4083 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004084 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004085 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004086 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004087 return false;
4088 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004089 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004090
Vladimir Markoe079e212016-05-25 12:49:49 +01004091 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004092 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004093 return false;
4094 }
4095 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004096 return true;
4097}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004098
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004099bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004100 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004101 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004102 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004103 return false;
4104 }
4105 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004106
Vladimir Markoe079e212016-05-25 12:49:49 +01004107 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004108 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004109 return false;
4110 }
4111 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4112 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004113
Vladimir Markoe079e212016-05-25 12:49:49 +01004114 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004115 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004116 return false;
4117 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004118 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004119 return true;
4120}
4121
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004122const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
4123 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004124 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004125 uint32_t utf16_length;
4126 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
4127 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
4128 InternTable::Utf8String string(utf16_length,
4129 utf8_data,
4130 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
4131 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
4132 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
4133 auto it = table.Find(string);
4134 if (it != table.end()) {
4135 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4136 }
4137 }
4138 LOG(FATAL) << "Did not find boot image string " << utf8_data;
4139 UNREACHABLE();
4140}
4141
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004142const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
4143 dex::TypeIndex type_idx)
4144 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
4145 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
4146 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
4147 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
4148 for (const ClassTable::ClassSet& class_set : table->classes_) {
4149 auto it = class_set.Find(pair);
4150 if (it != class_set.end()) {
4151 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4152 }
4153 }
4154 LOG(FATAL) << "Did not find boot image class " << descriptor;
4155 UNREACHABLE();
4156}
4157
Vladimir Marko74527972016-11-29 15:57:32 +00004158} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004159} // namespace art