blob: d261679ac17cd4837e1b6ce32d8d460cdd81e264 [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"
Andreas Gampe170331f2017-12-07 18:41:03 -080029#include "base/logging.h" // For VLOG
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070032#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010033#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010034#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000035#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000036#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000037#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070038#include "dex_file_loader.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070039#include "dex_file_types.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070040#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070041#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000042#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010043#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070044#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030045#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010046#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010047#include "linker/buffered_output_stream.h"
48#include "linker/file_output_stream.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000049#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010050#include "linker/linker_patch.h"
Vladimir Marko944da602016-02-19 12:27:55 +000051#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000052#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/array.h"
54#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010055#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070056#include "mirror/object-inl.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070057#include "standard_dex_file.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010058#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070059#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070060#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070061#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030062#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010063#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010064#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010065#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000066#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070067
68namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000069namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070070
Vladimir Marko9bdf1082016-01-21 12:15:52 +000071namespace { // anonymous namespace
72
Mathieu Chartier120aa282017-08-05 16:03:03 -070073// If we write dex layout info in the oat file.
74static constexpr bool kWriteDexLayoutInfo = true;
75
Igor Murashkin545412b2017-08-17 15:26:54 -070076// Force the OAT method layout to be sorted-by-name instead of
77// the default (class_def_idx, method_idx).
78//
79// Otherwise if profiles are used, that will act as
80// the primary sort order.
81//
82// A bit easier to use for development since oatdump can easily
83// show that things are being re-ordered when two methods aren't adjacent.
84static constexpr bool kOatWriterForceOatCodeLayout = false;
85
86static constexpr bool kOatWriterDebugOatCodeLayout = false;
87
Vladimir Marko9bdf1082016-01-21 12:15:52 +000088typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
89
90const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
91 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
92}
93
Vladimir Markoe079e212016-05-25 12:49:49 +010094class ChecksumUpdatingOutputStream : public OutputStream {
95 public:
96 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
97 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
98
99 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
100 oat_header_->UpdateChecksum(buffer, byte_count);
101 return out_->WriteFully(buffer, byte_count);
102 }
103
104 off_t Seek(off_t offset, Whence whence) OVERRIDE {
105 return out_->Seek(offset, whence);
106 }
107
108 bool Flush() OVERRIDE {
109 return out_->Flush();
110 }
111
112 private:
113 OutputStream* const out_;
114 OatHeader* const oat_header_;
115};
116
Vladimir Marko0c737df2016-08-01 16:33:16 +0100117inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
118 // We want to align the code rather than the preheader.
119 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
120 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
121 return aligned_code_offset - unaligned_code_offset;
122}
123
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000124} // anonymous namespace
125
126// Defines the location of the raw dex file to write.
127class OatWriter::DexFileSource {
128 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800129 enum Type {
130 kNone,
131 kZipEntry,
132 kRawFile,
133 kRawData,
134 };
135
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000136 explicit DexFileSource(ZipEntry* zip_entry)
137 : type_(kZipEntry), source_(zip_entry) {
138 DCHECK(source_ != nullptr);
139 }
140
141 explicit DexFileSource(File* raw_file)
142 : type_(kRawFile), source_(raw_file) {
143 DCHECK(source_ != nullptr);
144 }
145
146 explicit DexFileSource(const uint8_t* dex_file)
147 : type_(kRawData), source_(dex_file) {
148 DCHECK(source_ != nullptr);
149 }
150
Mathieu Chartier497d5262017-02-28 20:17:30 -0800151 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000152 bool IsZipEntry() const { return type_ == kZipEntry; }
153 bool IsRawFile() const { return type_ == kRawFile; }
154 bool IsRawData() const { return type_ == kRawData; }
155
156 ZipEntry* GetZipEntry() const {
157 DCHECK(IsZipEntry());
158 DCHECK(source_ != nullptr);
159 return static_cast<ZipEntry*>(const_cast<void*>(source_));
160 }
161
162 File* GetRawFile() const {
163 DCHECK(IsRawFile());
164 DCHECK(source_ != nullptr);
165 return static_cast<File*>(const_cast<void*>(source_));
166 }
167
168 const uint8_t* GetRawData() const {
169 DCHECK(IsRawData());
170 DCHECK(source_ != nullptr);
171 return static_cast<const uint8_t*>(source_);
172 }
173
174 void Clear() {
175 type_ = kNone;
176 source_ = nullptr;
177 }
178
179 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000180 Type type_;
181 const void* source_;
182};
183
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700184// OatClassHeader is the header only part of the oat class that is required even when compilation
185// is not enabled.
186class OatWriter::OatClassHeader {
187 public:
188 OatClassHeader(uint32_t offset,
189 uint32_t num_non_null_compiled_methods,
190 uint32_t num_methods,
191 mirror::Class::Status status)
192 : status_(status),
193 offset_(offset) {
194 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
195 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
196 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
197 if (num_non_null_compiled_methods == 0) {
198 type_ = kOatClassNoneCompiled;
199 } else if (num_non_null_compiled_methods == num_methods) {
200 type_ = kOatClassAllCompiled;
201 } else {
202 type_ = kOatClassSomeCompiled;
203 }
204 }
205
206 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
207
208 static size_t SizeOf() {
209 return sizeof(status_) + sizeof(type_);
210 }
211
212 // Data to write.
213 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
214 int16_t status_;
215
216 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
217 uint16_t type_;
218
219 // Offset of start of OatClass from beginning of OatHeader. It is
220 // used to validate file position when writing.
221 uint32_t offset_;
222};
223
224// The actual oat class body contains the information about compiled methods. It is only required
225// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000226class OatWriter::OatClass {
227 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700228 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100229 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700230 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000231 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000232 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700233 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000234
235 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
236 return compiled_methods_[class_def_method_index];
237 }
238
Vladimir Marko49b0f452015-12-10 13:49:19 +0000239 // CompiledMethods for each class_def_method_index, or null if no method is available.
240 dchecked_vector<CompiledMethod*> compiled_methods_;
241
242 // Offset from OatClass::offset_ to the OatMethodOffsets for the
243 // class_def_method_index. If 0, it means the corresponding
244 // CompiledMethod entry in OatClass::compiled_methods_ should be
245 // null and that the OatClass::type_ should be kOatClassBitmap.
246 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
247
248 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000249 uint32_t method_bitmap_size_;
250
251 // bit vector indexed by ClassDef method index. When
252 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
253 // method has an OatMethodOffsets in methods_offsets_, otherwise
254 // the entry was ommited to save space. If OatClassType::type_ is
255 // not is kOatClassBitmap, the bitmap will be null.
256 std::unique_ptr<BitVector> method_bitmap_;
257
258 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
259 // present in the OatClass. Note that some may be missing if
260 // OatClass::compiled_methods_ contains null values (and
261 // oat_method_offsets_offsets_from_oat_class_ should contain 0
262 // values in this case).
263 dchecked_vector<OatMethodOffsets> method_offsets_;
264 dchecked_vector<OatQuickMethodHeader> method_headers_;
265
266 private:
267 size_t GetMethodOffsetsRawSize() const {
268 return method_offsets_.size() * sizeof(method_offsets_[0]);
269 }
270
271 DISALLOW_COPY_AND_ASSIGN(OatClass);
272};
273
274class OatWriter::OatDexFile {
275 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000276 OatDexFile(const char* dex_file_location,
277 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000278 CreateTypeLookupTable create_type_lookup_table,
279 uint32_t dex_file_location_checksun,
280 size_t dex_file_size);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000281 OatDexFile(OatDexFile&& src) = default;
282
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000283 const char* GetLocation() const {
284 return dex_file_location_data_;
285 }
286
Vladimir Marko49b0f452015-12-10 13:49:19 +0000287 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000288 bool Write(OatWriter* oat_writer, OutputStream* out) const;
289 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
290
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100291 size_t GetClassOffsetsRawSize() const {
292 return class_offsets_.size() * sizeof(class_offsets_[0]);
293 }
294
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000295 // The source of the dex file.
296 DexFileSource source_;
297
298 // Whether to create the type lookup table.
299 CreateTypeLookupTable create_type_lookup_table_;
300
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000301 // Dex file size. Passed in the constructor, but could be
302 // overwritten by LayoutAndWriteDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000303 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000304
305 // Offset of start of OatDexFile from beginning of OatHeader. It is
306 // used to validate file position when writing.
307 size_t offset_;
308
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000309 ///// Start of data to write to vdex/oat file.
310
311 const uint32_t dex_file_location_size_;
312 const char* const dex_file_location_data_;
313
314 // The checksum of the dex file.
315 const uint32_t dex_file_location_checksum_;
316
317 // Offset of the dex file in the vdex file. Set when writing dex files in
318 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000319 uint32_t dex_file_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000320
321 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000322 uint32_t lookup_table_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000323
324 // Class and BSS offsets set in PrepareLayout.
325 uint32_t class_offsets_offset_;
Nicolas Geoffray715d6722017-11-20 22:28:46 +0000326 uint32_t method_bss_mapping_offset_;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000327 uint32_t type_bss_mapping_offset_;
328 uint32_t string_bss_mapping_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000329
330 // Offset of dex sections that will have different runtime madvise states.
331 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700332 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000333
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000334 // Data to write to a separate section. We set the length
335 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000336 dchecked_vector<uint32_t> class_offsets_;
337
Mathieu Chartier120aa282017-08-05 16:03:03 -0700338 // Dex section layout info to serialize.
339 DexLayoutSections dex_sections_layout_;
340
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000341 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000342 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000343 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
344};
345
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100346#define DCHECK_OFFSET() \
347 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
348 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
349
350#define DCHECK_OFFSET_() \
351 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
352 << "file_offset=" << file_offset << " offset_=" << offset_
353
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700354OatWriter::OatWriter(bool compiling_boot_image,
355 TimingLogger* timings,
356 ProfileCompilationInfo* info,
357 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000358 : write_state_(WriteState::kAddingDexFileSources),
359 timings_(timings),
360 raw_dex_files_(),
361 zip_archives_(),
362 zipped_dex_files_(),
363 zipped_dex_file_locations_(),
364 compiler_driver_(nullptr),
365 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800366 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000367 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100368 vdex_size_(0u),
369 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100370 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100371 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100372 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000373 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000374 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100375 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000376 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100377 bss_method_entry_references_(),
378 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000379 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000380 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100381 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100382 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700383 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100384 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000385 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700386 size_dex_file_alignment_(0),
387 size_executable_offset_alignment_(0),
388 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700389 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700390 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100391 size_verifier_deps_(0),
392 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100393 size_quickening_info_(0),
394 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700395 size_interpreter_to_interpreter_bridge_(0),
396 size_interpreter_to_compiled_code_bridge_(0),
397 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800398 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700399 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700400 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700401 size_quick_to_interpreter_bridge_(0),
402 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100403 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700404 size_code_(0),
405 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100406 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100407 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700408 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700409 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700410 size_oat_dex_file_location_size_(0),
411 size_oat_dex_file_location_data_(0),
412 size_oat_dex_file_location_checksum_(0),
413 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000414 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000415 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700416 size_oat_dex_file_dex_layout_sections_offset_(0),
417 size_oat_dex_file_dex_layout_sections_(0),
418 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100419 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000420 size_oat_dex_file_type_bss_mapping_offset_(0),
421 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000422 size_oat_lookup_table_alignment_(0),
423 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000424 size_oat_class_offsets_alignment_(0),
425 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700426 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700427 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700428 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100429 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100430 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000431 size_type_bss_mappings_(0u),
432 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000433 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700434 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700435 profile_compilation_info_(info),
436 compact_dex_level_(compact_dex_level) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000437}
438
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000439static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
440 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
441 if (!valid_standard_dex_magic) {
442 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
443 return false;
444 }
445 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
446 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
447 return false;
448 }
449 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
450 if (header->file_size_ < sizeof(DexFile::Header)) {
451 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
452 << " File: " << location;
453 return false;
454 }
455 return true;
456}
457
458static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
459 uint8_t* raw_header,
460 const char* location) {
461 // Read the dex file header and perform minimal verification.
462 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
463 PLOG(ERROR) << "Failed to read dex file header. Actual: "
464 << " File: " << location << " Output: " << file->GetPath();
465 return nullptr;
466 }
467 if (!ValidateDexFileHeader(raw_header, location)) {
468 return nullptr;
469 }
470
471 return AsUnalignedDexFileHeader(raw_header);
472}
473
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000474bool OatWriter::AddDexFileSource(const char* filename,
475 const char* location,
476 CreateTypeLookupTable create_type_lookup_table) {
477 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
478 uint32_t magic;
479 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700480 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
481 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000482 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
483 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700484 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000485 uint8_t raw_header[sizeof(DexFile::Header)];
486 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
487 if (header == nullptr) {
488 return false;
489 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490 // The file is open for reading, not writing, so it's OK to let the File destructor
491 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700492 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000493 oat_dex_files_.emplace_back(/* OatDexFile */
494 location,
495 DexFileSource(raw_dex_files_.back().get()),
496 create_type_lookup_table,
497 header->checksum_,
498 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000499 } else if (IsZipMagic(magic)) {
500 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
501 return false;
502 }
503 } else {
504 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
505 return false;
506 }
507 return true;
508}
509
510// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700511bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000512 const char* location,
513 CreateTypeLookupTable create_type_lookup_table) {
514 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
515 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700516 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000517 ZipArchive* zip_archive = zip_archives_.back().get();
518 if (zip_archive == nullptr) {
519 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
520 << error_msg;
521 return false;
522 }
523 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700524 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000525 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
526 if (entry == nullptr) {
527 break;
528 }
529 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700530 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000531 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000532 // We override the checksum from header with the CRC from ZIP entry.
533 oat_dex_files_.emplace_back(/* OatDexFile */
534 full_location,
535 DexFileSource(zipped_dex_files_.back().get()),
536 create_type_lookup_table,
537 zipped_dex_files_.back()->GetCrc32(),
538 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000539 }
540 if (zipped_dex_file_locations_.empty()) {
541 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
542 return false;
543 }
544 return true;
545}
546
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000547// Add dex file source(s) from a vdex file specified by a file handle.
548bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
549 const char* location,
550 CreateTypeLookupTable create_type_lookup_table) {
551 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
552 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000553 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000554 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
555 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000556 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
557 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000558 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700559
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700560 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000561 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
562 return false;
563 }
564 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700565 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000566 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000567 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
568 oat_dex_files_.emplace_back(/* OatDexFile */
569 full_location,
570 DexFileSource(current_dex_data),
571 create_type_lookup_table,
572 vdex_file.GetLocationChecksum(i),
573 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000574 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000575
576 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
577 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
578 return false;
579 }
580
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000581 if (oat_dex_files_.empty()) {
582 LOG(ERROR) << "No dex files in vdex file created from " << location;
583 return false;
584 }
585 return true;
586}
587
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000588// Add dex file source from raw memory.
589bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
590 const char* location,
591 uint32_t location_checksum,
592 CreateTypeLookupTable create_type_lookup_table) {
593 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
594 if (data.size() < sizeof(DexFile::Header)) {
595 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
596 << data.size() << " File: " << location;
597 return false;
598 }
599 if (!ValidateDexFileHeader(data.data(), location)) {
600 return false;
601 }
602 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
603 if (data.size() < header->file_size_) {
604 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
605 << " file size from header: " << header->file_size_ << " File: " << location;
606 return false;
607 }
608
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000609 oat_dex_files_.emplace_back(/* OatDexFile */
610 location,
611 DexFileSource(data.data()),
612 create_type_lookup_table,
613 location_checksum,
614 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000615 return true;
616}
617
Calin Juravle1ce70852017-06-28 10:59:03 -0700618dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
619 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000620 locations.reserve(oat_dex_files_.size());
621 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
622 locations.push_back(oat_dex_file.GetLocation());
623 }
624 return locations;
625}
626
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700627bool OatWriter::MayHaveCompiledMethods() const {
628 return CompilerFilter::IsAnyCompilationEnabled(
629 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
630}
631
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000632bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100633 File* vdex_file,
634 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000635 InstructionSet instruction_set,
636 const InstructionSetFeatures* instruction_set_features,
637 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800638 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000639 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000640 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
641 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
642 CHECK(write_state_ == WriteState::kAddingDexFileSources);
643
David Brazdil7b49e6c2016-09-01 11:06:18 +0100644 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
645 if (!RecordOatDataOffset(oat_rodata)) {
646 return false;
647 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000648
649 std::unique_ptr<MemMap> dex_files_map;
650 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100651
652 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000653
654 // Reserve space for Vdex header and checksums.
655 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100656 oat_size_ = InitOatHeader(instruction_set,
657 instruction_set_features,
658 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
659 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100660
661 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
662
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000663 std::unique_ptr<BufferedOutputStream> vdex_out =
664 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
665 // Write DEX files into VDEX, mmap and open them.
666 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
667 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
668 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000669 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000670
Mathieu Chartier120aa282017-08-05 16:03:03 -0700671 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000672 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
673 return false;
674 }
675
Mathieu Chartier120aa282017-08-05 16:03:03 -0700676 // Write dex layout sections into the oat file.
677 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
678 return false;
679 }
680
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000681 *opened_dex_files_map = std::move(dex_files_map);
682 *opened_dex_files = std::move(dex_files);
683 write_state_ = WriteState::kPrepareLayout;
684 return true;
685}
686
Vladimir Marko74527972016-11-29 15:57:32 +0000687void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000688 CHECK(write_state_ == WriteState::kPrepareLayout);
689
Vladimir Marko944da602016-02-19 12:27:55 +0000690 relative_patcher_ = relative_patcher;
691 SetMultiOatRelativePatcherAdjustment();
692
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000693 if (compiling_boot_image_) {
694 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800695 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100696 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000697 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100698
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100699 {
700 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
701 InitBssLayout(instruction_set);
702 }
703
David Brazdil7b49e6c2016-09-01 11:06:18 +0100704 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800705 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100706 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
707 offset = InitClassOffsets(offset);
708 }
709 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000710 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800711 offset = InitOatClasses(offset);
712 }
713 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000714 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
715 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100716 }
717 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000718 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100719 offset = InitOatMaps(offset);
720 }
721 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100722 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
723 oat_header_->SetOatDexFilesOffset(offset);
724 offset = InitOatDexFiles(offset);
725 }
726 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000727 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800728 offset = InitOatCode(offset);
729 }
730 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000731 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800732 offset = InitOatCodeDexFiles(offset);
733 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100734 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100735 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100736
Brian Carlstrome24fa612011-09-29 00:53:55 -0700737 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800738 if (compiling_boot_image_) {
739 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000740 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800741 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000742
743 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700744}
745
Ian Rogers0571d352011-11-03 19:51:38 -0700746OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700747}
748
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100749class OatWriter::DexMethodVisitor {
750 public:
751 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100752 : writer_(writer),
753 offset_(offset),
754 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700755 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100756
757 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
758 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700759 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100760 dex_file_ = dex_file;
761 class_def_index_ = class_def_index;
762 return true;
763 }
764
765 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
766
767 virtual bool EndClass() {
768 if (kIsDebugBuild) {
769 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700770 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100771 }
772 return true;
773 }
774
775 size_t GetOffset() const {
776 return offset_;
777 }
778
779 protected:
780 virtual ~DexMethodVisitor() { }
781
782 OatWriter* const writer_;
783
784 // The offset is usually advanced for each visited method by the derived class.
785 size_t offset_;
786
787 // The dex file and class def index are set in StartClass().
788 const DexFile* dex_file_;
789 size_t class_def_index_;
790};
791
792class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
793 public:
794 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100795 : DexMethodVisitor(writer, offset),
796 oat_class_index_(0u),
797 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100798
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100799 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100800 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700801 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
802 // There are no oat classes if there aren't any compiled methods.
803 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
804 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100805 method_offsets_index_ = 0u;
806 return true;
807 }
808
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100809 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100810 ++oat_class_index_;
811 return DexMethodVisitor::EndClass();
812 }
813
814 protected:
815 size_t oat_class_index_;
816 size_t method_offsets_index_;
817};
818
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100819static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000820 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100821}
822
823static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000824 // The dextodexcompiler puts the quickening info table into the CompiledMethod
825 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100826 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
827}
828
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100829class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
830 public:
831 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
832 : DexMethodVisitor(writer, /* offset */ 0u) {}
833
834 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
835 const ClassDataItemIterator& it) OVERRIDE {
836 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
837 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
838 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100839 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100840 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
841 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
842 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000843 AddBssReference(target_method,
844 target_method.dex_file->NumMethodIds(),
845 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100846 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
847 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000848 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
849 AddBssReference(target_type,
850 target_type.dex_file->NumTypeIds(),
851 &writer_->bss_type_entry_references_);
852 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100853 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000854 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
855 AddBssReference(target_string,
856 target_string.dex_file->NumStringIds(),
857 &writer_->bss_string_entry_references_);
858 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100859 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
860 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100861 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100862 }
863 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100864 } else {
865 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100866 }
867 return true;
868 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000869
870 private:
871 void AddBssReference(const DexFileReference& ref,
872 size_t number_of_indexes,
873 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
874 // We currently support inlining of throwing instructions only when they originate in the
875 // same dex file as the outer method. All .bss references are used by throwing instructions.
876 DCHECK_EQ(dex_file_, ref.dex_file);
877
878 auto refs_it = references->find(ref.dex_file);
879 if (refs_it == references->end()) {
880 refs_it = references->Put(
881 ref.dex_file,
882 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
883 refs_it->second.ClearAllBits();
884 }
885 refs_it->second.SetBit(ref.index);
886 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100887};
888
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100889class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
890 public:
891 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100892 : DexMethodVisitor(writer, offset),
893 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100894 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000895 size_t num_classes = 0u;
896 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
897 num_classes += oat_dex_file.class_offsets_.size();
898 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700899 // If we aren't compiling only reserve headers.
900 writer_->oat_class_headers_.reserve(num_classes);
901 if (writer->MayHaveCompiledMethods()) {
902 writer->oat_classes_.reserve(num_classes);
903 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100904 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100905 // If there are any classes, the class offsets allocation aligns the offset.
906 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100907 }
908
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100909 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100910 DexMethodVisitor::StartClass(dex_file, class_def_index);
911 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100912 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100913 return true;
914 }
915
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300916 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100917 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100918 // Fill in the compiled_methods_ array for methods that have a
919 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100920 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100921 // OatMethodOffsets for the compiled methods.
922 uint32_t method_idx = it.GetMemberIndex();
923 CompiledMethod* compiled_method =
924 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
925 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100926 if (HasCompiledCode(compiled_method)) {
927 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100928 }
929 return true;
930 }
931
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100932 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100933 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100934 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700935 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
936 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700937 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
938 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700939 // The oat class status is used only for verification of resolved classes,
940 // so use kStatusErrorResolved whether the class was resolved or unresolved
941 // during compile-time verification.
942 status = mirror::Class::kStatusErrorResolved;
943 } else {
944 status = mirror::Class::kStatusNotReady;
945 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946 }
947
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700948 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100949 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700950 compiled_methods_.size(),
951 status);
952 OatClassHeader& header = writer_->oat_class_headers_.back();
953 offset_ += header.SizeOf();
954 if (writer_->MayHaveCompiledMethods()) {
955 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100956 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700957 header.type_);
958 offset_ += writer_->oat_classes_.back().SizeOf();
959 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100960 return DexMethodVisitor::EndClass();
961 }
962
963 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000964 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100965 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100966};
967
Igor Murashkin545412b2017-08-17 15:26:54 -0700968// CompiledMethod + metadata required to do ordered method layout.
969//
970// See also OrderedMethodVisitor.
971struct OatWriter::OrderedMethodData {
972 ProfileCompilationInfo::MethodHotness method_hotness;
973 OatClass* oat_class;
974 CompiledMethod* compiled_method;
975 MethodReference method_reference;
976 size_t method_offsets_index;
977
978 size_t class_def_index;
979 uint32_t access_flags;
980 const DexFile::CodeItem* code_item;
981
982 // A value of -1 denotes missing debug info
983 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
984 // Index into writer_->method_info_
985 size_t debug_info_idx;
986
987 bool HasDebugInfo() const {
988 return debug_info_idx != kDebugInfoIdxInvalid;
989 }
990
991 // Bin each method according to the profile flags.
992 //
993 // Groups by e.g.
994 // -- not hot at all
995 // -- hot
996 // -- hot and startup
997 // -- hot and post-startup
998 // -- hot and startup and poststartup
999 // -- startup
1000 // -- startup and post-startup
1001 // -- post-startup
1002 //
1003 // (See MethodHotness enum definition for up-to-date binning order.)
1004 bool operator<(const OrderedMethodData& other) const {
1005 if (kOatWriterForceOatCodeLayout) {
1006 // Development flag: Override default behavior by sorting by name.
1007
1008 std::string name = method_reference.PrettyMethod();
1009 std::string other_name = other.method_reference.PrettyMethod();
1010 return name < other_name;
1011 }
1012
1013 // Use the profile's method hotness to determine sort order.
1014 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1015 return true;
1016 }
1017
1018 // Default: retain the original order.
1019 return false;
1020 }
1021
1022 private:
1023 // Used to determine relative order for OAT code layout when determining
1024 // binning.
1025 size_t GetMethodHotnessOrder() const {
1026 bool hotness[] = {
1027 method_hotness.IsHot(),
1028 method_hotness.IsStartup(),
1029 method_hotness.IsPostStartup()
1030 };
1031
1032
1033 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1034 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1035 // time that memory is referenced in the process.
1036
1037 size_t hotness_bits = 0;
1038 for (size_t i = 0; i < arraysize(hotness); ++i) {
1039 if (hotness[i]) {
1040 hotness_bits |= (1 << i);
1041 }
1042 }
1043
1044 if (kIsDebugBuild) {
1045 // Check for bins that are always-empty given a real profile.
1046 if (method_hotness.IsHot() &&
1047 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1048 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001049 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1050 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001051 // This is not fatal, so only warn.
1052 }
1053 }
1054
1055 return hotness_bits;
1056 }
1057};
1058
1059// Given a queue of CompiledMethod in some total order,
1060// visit each one in that order.
1061class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001062 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001063 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1064 : ordered_methods_(std::move(ordered_methods)) {
1065 }
1066
1067 virtual ~OrderedMethodVisitor() {}
1068
1069 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1070 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1071 if (!VisitStart()) {
1072 return false;
1073 }
1074
1075 for (const OrderedMethodData& method_data : ordered_methods_) {
1076 if (!VisitMethod(method_data)) {
1077 return false;
1078 }
1079 }
1080
1081 return VisitComplete();
1082 }
1083
1084 // Invoked once at the beginning, prior to visiting anything else.
1085 //
1086 // Return false to abort further visiting.
1087 virtual bool VisitStart() { return true; }
1088
1089 // Invoked repeatedly in the order specified by `ordered_methods`.
1090 //
1091 // Return false to short-circuit and to stop visiting further methods.
1092 virtual bool VisitMethod(const OrderedMethodData& method_data)
1093 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1094
1095 // Invoked once at the end, after every other method has been successfully visited.
1096 //
1097 // Return false to indicate the overall `Visit` has failed.
1098 virtual bool VisitComplete() = 0;
1099
1100 OrderedMethodList ReleaseOrderedMethods() {
1101 return std::move(ordered_methods_);
1102 }
1103
1104 private:
1105 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1106 // Methods can be inserted more than once in case of duplicated methods.
1107 OrderedMethodList ordered_methods_;
1108};
1109
1110// Visit every compiled method in order to determine its order within the OAT file.
1111// Methods from the same class do not need to be adjacent in the OAT code.
1112class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1113 public:
1114 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1115 : OatDexMethodVisitor(writer, offset) {
1116 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001117
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001118 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001119 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001120 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001121 }
1122
Igor Murashkin545412b2017-08-17 15:26:54 -07001123 bool VisitMethod(size_t class_def_method_index,
1124 const ClassDataItemIterator& it)
1125 OVERRIDE
1126 REQUIRES_SHARED(Locks::mutator_lock_) {
1127 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1128
Vladimir Marko49b0f452015-12-10 13:49:19 +00001129 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001130 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1131
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001132 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001133 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001134
Igor Murashkin545412b2017-08-17 15:26:54 -07001135 {
1136 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1137 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1138 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001139
Igor Murashkin545412b2017-08-17 15:26:54 -07001140 // Debug method info must be pushed in the original order
1141 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1142 // ElfCompilationUnitWriter::Write requires this.
1143 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1144 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1145 writer_->method_info_.push_back(info);
1146
1147 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1148 // once we know the offsets.
1149 //
1150 // Store the index into writer_->method_info_ since future push-backs
1151 // could reallocate and change the underlying data address.
1152 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001153 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001154 }
1155
1156 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1157
1158 // Lookup method hotness from profile, if available.
1159 // Otherwise assume a default of none-hotness.
1160 ProfileCompilationInfo::MethodHotness method_hotness =
1161 writer_->profile_compilation_info_ != nullptr
1162 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1163 : ProfileCompilationInfo::MethodHotness();
1164
1165 // Handle duplicate methods by pushing them repeatedly.
1166 OrderedMethodData method_data = {
1167 method_hotness,
1168 oat_class,
1169 compiled_method,
1170 method_ref,
1171 method_offsets_index_,
1172 class_def_index_,
1173 it.GetMethodAccessFlags(),
1174 it.GetMethodCodeItem(),
1175 debug_info_idx
1176 };
1177 ordered_methods_.push_back(method_data);
1178
1179 method_offsets_index_++;
1180 }
1181
1182 return true;
1183 }
1184
1185 OrderedMethodList ReleaseOrderedMethods() {
1186 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1187 // Sort by the method ordering criteria (in OrderedMethodData).
1188 // Since most methods will have the same ordering criteria,
1189 // we preserve the original insertion order within the same sort order.
1190 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1191 } else {
1192 // The profile-less behavior is as if every method had 0 hotness
1193 // associated with it.
1194 //
1195 // Since sorting all methods with hotness=0 should give back the same
1196 // order as before, don't do anything.
1197 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1198 }
1199
1200 return std::move(ordered_methods_);
1201 }
1202
1203 private:
1204 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1205 // Methods can be inserted more than once in case of duplicated methods.
1206 OrderedMethodList ordered_methods_;
1207};
1208
1209// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1210class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1211 public:
1212 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1213 size_t offset,
1214 OrderedMethodList ordered_methods)
1215 : LayoutReserveOffsetCodeMethodVisitor(writer,
1216 offset,
1217 writer->GetCompilerDriver()->GetCompilerOptions(),
1218 std::move(ordered_methods)) {
1219 }
1220
1221 virtual bool VisitComplete() OVERRIDE {
1222 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1223 if (generate_debug_info_) {
1224 std::vector<debug::MethodDebugInfo> thunk_infos =
1225 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1226 writer_->method_info_.insert(writer_->method_info_.end(),
1227 std::make_move_iterator(thunk_infos.begin()),
1228 std::make_move_iterator(thunk_infos.end()));
1229 }
1230 return true;
1231 }
1232
1233 virtual bool VisitMethod(const OrderedMethodData& method_data)
1234 OVERRIDE
1235 REQUIRES_SHARED(Locks::mutator_lock_) {
1236 OatClass* oat_class = method_data.oat_class;
1237 CompiledMethod* compiled_method = method_data.compiled_method;
1238 const MethodReference& method_ref = method_data.method_reference;
1239 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1240 size_t class_def_index = method_data.class_def_index;
1241 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001242 bool has_debug_info = method_data.HasDebugInfo();
1243 size_t debug_info_idx = method_data.debug_info_idx;
1244
1245 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1246
1247 // Derived from CompiledMethod.
1248 uint32_t quick_code_offset = 0;
1249
1250 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1251 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1252 uint32_t thumb_offset = compiled_method->CodeDelta();
1253
1254 // Deduplicate code arrays if we are not producing debuggable code.
1255 bool deduped = true;
1256 if (debuggable_) {
1257 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1258 if (quick_code_offset != 0u) {
1259 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1260 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001261 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001262 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1263 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001264 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001265 } else {
1266 quick_code_offset = dedupe_map_.GetOrCreate(
1267 compiled_method,
1268 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1269 deduped = false;
1270 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1271 });
1272 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001273
Igor Murashkin545412b2017-08-17 15:26:54 -07001274 if (code_size != 0) {
1275 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1276 // TODO: Should this be a hard failure?
1277 LOG(WARNING) << "Multiple definitions of "
1278 << method_ref.dex_file->PrettyMethod(method_ref.index)
1279 << " offsets " << relative_patcher_->GetOffset(method_ref)
1280 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001281 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001282 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1283 }
1284 }
1285
1286 // Update quick method header.
1287 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1288 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1289 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1290 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1291 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1292 // to 0-offset and we need to adjust it by code_offset.
1293 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001294 CHECK(!compiled_method->GetQuickCode().empty());
1295 // If the code is compiled, we write the offset of the stack map relative
1296 // to the code.
1297 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001298 vmap_table_offset += code_offset;
1299 DCHECK_LT(vmap_table_offset, code_offset);
1300 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001301 if (method_info_offset != 0u) {
1302 method_info_offset += code_offset;
1303 DCHECK_LT(method_info_offset, code_offset);
1304 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001305 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1306 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1307 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1308 *method_header = OatQuickMethodHeader(vmap_table_offset,
1309 method_info_offset,
1310 frame_size_in_bytes,
1311 core_spill_mask,
1312 fp_spill_mask,
1313 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001314
Igor Murashkin545412b2017-08-17 15:26:54 -07001315 if (!deduped) {
1316 // Update offsets. (Checksum is updated when writing.)
1317 offset_ += sizeof(*method_header); // Method header is prepended before code.
1318 offset_ += code_size;
1319 // Record absolute patch locations.
1320 if (!compiled_method->GetPatches().empty()) {
1321 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1322 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1323 if (!patch.IsPcRelative()) {
1324 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001325 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001326 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001327 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001328 }
1329
Igor Murashkin545412b2017-08-17 15:26:54 -07001330 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1331 if (generate_debug_info_ && code_size != 0) {
1332 DCHECK(has_debug_info);
1333
1334 bool has_code_info = method_header->IsOptimized();
1335 // Record debug information for this function if we are doing that.
1336 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1337 DCHECK(info.trampoline_name.empty());
1338 info.dex_file = method_ref.dex_file;
1339 info.class_def_index = class_def_index;
1340 info.dex_method_index = method_ref.index;
1341 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001342 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1343 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001344 info.isa = compiled_method->GetInstructionSet();
1345 info.deduped = deduped;
1346 info.is_native_debuggable = native_debuggable_;
1347 info.is_optimized = method_header->IsOptimized();
1348 info.is_code_address_text_relative = true;
1349 info.code_address = code_offset - executable_offset_;
1350 info.code_size = code_size;
1351 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1352 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1353 info.cfi = compiled_method->GetCFIInfo();
1354 } else {
1355 DCHECK(!has_debug_info);
1356 }
1357
1358 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1359 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1360 offsets->code_offset_ = quick_code_offset;
1361
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001362 return true;
1363 }
1364
Igor Murashkin545412b2017-08-17 15:26:54 -07001365 size_t GetOffset() const {
1366 return offset_;
1367 }
1368
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001369 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001370 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1371 size_t offset,
1372 const CompilerOptions& compiler_options,
1373 OrderedMethodList ordered_methods)
1374 : OrderedMethodVisitor(std::move(ordered_methods)),
1375 writer_(writer),
1376 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001377 relative_patcher_(writer->relative_patcher_),
1378 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1379 debuggable_(compiler_options.GetDebuggable()),
1380 native_debuggable_(compiler_options.GetNativeDebuggable()),
1381 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1382 writer->absolute_patch_locations_.reserve(
1383 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1384 }
1385
Vladimir Marko20f85592015-03-19 10:07:02 +00001386 struct CodeOffsetsKeyComparator {
1387 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001388 // Code is deduplicated by CompilerDriver, compare only data pointers.
1389 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1390 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001391 }
1392 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001393 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1394 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001395 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001396 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1397 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1398 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001399 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1400 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001401 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001402 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1403 return rhs->IsIntrinsic();
1404 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001405 return false;
1406 }
1407 };
1408
David Srbecky009e2a62015-04-15 02:46:30 +01001409 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001410 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001411 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001412 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001413 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1414 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001415 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1416 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1417 }
1418
Igor Murashkin545412b2017-08-17 15:26:54 -07001419 OatWriter* writer_;
1420
1421 // Offset of the code of the compiled methods.
1422 size_t offset_;
1423
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001424 // Deduplication is already done on a pointer basis by the compiler driver,
1425 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001426 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001427
Vladimir Marko1b404a82017-09-01 13:35:26 +01001428 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001429 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001430 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001431 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001432 const bool native_debuggable_;
1433 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001434};
1435
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001436class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1437 public:
1438 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001439 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001440
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001441 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001442 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001443 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001444 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1445
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001446 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001447 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001448 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001449
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001450 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1451 uint32_t map_size = map.size() * sizeof(map[0]);
1452 if (map_size != 0u) {
1453 size_t offset = dedupe_map_.GetOrCreate(
1454 map.data(),
1455 [this, map_size]() {
1456 uint32_t new_offset = offset_;
1457 offset_ += map_size;
1458 return new_offset;
1459 });
1460 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1461 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1462 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001463 }
1464 ++method_offsets_index_;
1465 }
1466
1467 return true;
1468 }
1469
1470 private:
1471 // Deduplication is already done on a pointer basis by the compiler driver,
1472 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001473 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001474};
1475
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001476class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1477 public:
1478 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1479
1480 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001481 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001482 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1483 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1484
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001485 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001486 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1487 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1488 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1489 const uint32_t map_size = map.size() * sizeof(map[0]);
1490 if (map_size != 0u) {
1491 size_t offset = dedupe_map_.GetOrCreate(
1492 map.data(),
1493 [this, map_size]() {
1494 uint32_t new_offset = offset_;
1495 offset_ += map_size;
1496 return new_offset;
1497 });
1498 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1499 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1500 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1501 }
1502 ++method_offsets_index_;
1503 }
1504
1505 return true;
1506 }
1507
1508 private:
1509 // Deduplication is already done on a pointer basis by the compiler driver,
1510 // so we can simply compare the pointers to find out if things are duplicated.
1511 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1512};
1513
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001514class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1515 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001516 InitImageMethodVisitor(OatWriter* writer,
1517 size_t offset,
1518 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001519 : OatDexMethodVisitor(writer, offset),
1520 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001521 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001522 dex_files_(dex_files),
1523 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001524
1525 // Handle copied methods here. Copy pointer to quick code from
1526 // an origin method to a copied method only if they are
1527 // in the same oat file. If the origin and the copied methods are
1528 // in different oat files don't touch the copied method.
1529 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001530 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001531 REQUIRES_SHARED(Locks::mutator_lock_) {
1532 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1533 // Skip classes that are not in the image.
1534 if (!IsImageClass()) {
1535 return true;
1536 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001537 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001538 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1539 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1540 if (klass != nullptr) {
1541 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1542 // Find origin method. Declaring class and dex_method_idx
1543 // in the copied method should be the same as in the origin
1544 // method.
1545 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001546 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001547 declaring_class->GetDexCache(),
1548 method.GetDexMethodIndex(),
1549 pointer_size_);
1550 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001551 CHECK(!origin->IsDirect());
1552 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001553 if (IsInOatFile(&declaring_class->GetDexFile())) {
1554 const void* code_ptr =
1555 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1556 if (code_ptr == nullptr) {
1557 methods_to_process_.push_back(std::make_pair(&method, origin));
1558 } else {
1559 method.SetEntryPointFromQuickCompiledCodePtrSize(
1560 code_ptr, pointer_size_);
1561 }
1562 }
1563 }
1564 }
1565 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001566 }
1567
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001568 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001569 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001570 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001571 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001572 return true;
1573 }
1574
Vladimir Marko49b0f452015-12-10 13:49:19 +00001575 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001576 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1577
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001578 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001579 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001580 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1581 offsets = oat_class->method_offsets_[method_offsets_index_];
1582 ++method_offsets_index_;
1583 }
1584
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001585 Thread* self = Thread::Current();
1586 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001587 ArtMethod* method;
1588 if (writer_->HasBootImage()) {
1589 const InvokeType invoke_type = it.GetMethodInvokeType(
1590 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001591 // Unchecked as we hold mutator_lock_ on entry.
1592 ScopedObjectAccessUnchecked soa(self);
1593 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001594 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001595 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>(),
Vladimir Marko89011192017-12-11 13:45:05 +00001598 /* referrer */ nullptr,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001599 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
Vladimir Marko28e012a2017-12-07 11:22:59 +00001954 ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1955 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001956 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001957 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001958 ObjPtr<mirror::Class> type =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001959 class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001960 CHECK(type != nullptr);
Vladimir Marko28e012a2017-12-07 11:22:59 +00001961 return type;
Vladimir Markof4da6752014-08-01 19:04:18 +01001962 }
1963
Vladimir Marko28e012a2017-12-07 11:22:59 +00001964 ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1965 REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001966 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Markoa64b52d2017-12-08 16:27:49 +00001967 ObjPtr<mirror::String> string =
1968 linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001969 DCHECK(string != nullptr);
1970 DCHECK(writer_->HasBootImage() ||
1971 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1972 return string;
1973 }
1974
Vladimir Marko65979462017-05-19 17:25:12 +01001975 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1976 DCHECK(writer_->HasBootImage());
1977 method = writer_->image_writer_->GetImageMethodAddress(method);
1978 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1979 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1980 // TODO: Clean up offset types. The target offset must be treated as signed.
1981 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1982 }
1983
Vladimir Marko28e012a2017-12-07 11:22:59 +00001984 uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
1985 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001986 DCHECK(writer_->HasBootImage());
Vladimir Marko28e012a2017-12-07 11:22:59 +00001987 object = writer_->image_writer_->GetImageAddress(object.Ptr());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001988 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1989 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1990 // TODO: Clean up offset types. The target offset must be treated as signed.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001991 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001992 }
1993
Vladimir Markof4da6752014-08-01 19:04:18 +01001994 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001995 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001996 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001997 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001998 } else {
1999 // NOTE: We're using linker patches for app->boot references when the image can
2000 // be relocated and therefore we need to emit .oat_patches. We're not using this
2001 // for app->app references, so check that the object is in the image space.
2002 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01002003 }
Vladimir Marko09d09432015-09-08 13:47:48 +01002004 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01002005 uint32_t address = PointerToLowMemUInt32(object);
2006 DCHECK_LE(offset + 4, code->size());
2007 uint8_t* data = &(*code)[offset];
2008 data[0] = address & 0xffu;
2009 data[1] = (address >> 8) & 0xffu;
2010 data[2] = (address >> 16) & 0xffu;
2011 data[3] = (address >> 24) & 0xffu;
2012 }
2013
2014 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002015 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01002016 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002017 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002018 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
2019 // TODO: Clean up offset types.
2020 // The target_offset must be treated as signed for cross-oat patching.
2021 const void* target = reinterpret_cast<const void*>(
2022 writer_->image_writer_->GetOatDataBegin(oat_index) +
2023 static_cast<int32_t>(target_offset));
2024 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01002025 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002026 DCHECK_LE(offset + 4, code->size());
2027 uint8_t* data = &(*code)[offset];
2028 data[0] = address & 0xffu;
2029 data[1] = (address >> 8) & 0xffu;
2030 data[2] = (address >> 16) & 0xffu;
2031 data[3] = (address >> 24) & 0xffu;
2032 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002033
2034 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
2035 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
2036 REQUIRES_SHARED(Locks::mutator_lock_) {
2037 DCHECK(!writer_->HasBootImage());
2038 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
2039 *patch.TargetStringDexFile(), patch.TargetStringIndex());
2040 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002041 return GetBootImageTableEntryOffset(string_root);
2042 }
2043
2044 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
2045 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
2046 REQUIRES_SHARED(Locks::mutator_lock_) {
2047 DCHECK(!writer_->HasBootImage());
2048 const uint8_t* table_slot =
2049 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
2050 DCHECK(table_slot != nullptr);
2051 return GetBootImageTableEntryOffset(table_slot);
2052 }
2053
2054 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002055 uint32_t base_offset = writer_->bss_start_;
2056 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2057 const uint8_t* const_tables_begin =
2058 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002059 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002060 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
2061 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
2062 return base_offset + offset;
2063 }
2064 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
2065 }
2066 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
2067 UNREACHABLE();
2068 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002069};
2070
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002071class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2072 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002073 WriteMapMethodVisitor(OatWriter* writer,
2074 OutputStream* out,
2075 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002076 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002077 : OatDexMethodVisitor(writer, relative_offset),
2078 out_(out),
2079 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002080
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002081 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002082 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002083 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2084
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002085 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002086 size_t file_offset = file_offset_;
2087 OutputStream* out = out_;
2088
Mingyao Yang063fc772016-08-02 11:02:54 -07002089 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002090 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002091 ++method_offsets_index_;
2092
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002093 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2094 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2095 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002096 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002097
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002098 // If vdex is enabled, only emit the map for compiled code. The quickening info
2099 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002100 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002101 // Transform map_offset to actual oat data offset.
2102 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2103 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002104 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002105
2106 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2107 size_t map_size = map.size() * sizeof(map[0]);
2108 if (map_offset == offset_) {
2109 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002110 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002111 ReportWriteFailure(it);
2112 return false;
2113 }
2114 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002115 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002116 }
2117 DCHECK_OFFSET_();
2118 }
2119
2120 return true;
2121 }
2122
2123 private:
2124 OutputStream* const out_;
2125 size_t const file_offset_;
2126
2127 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002128 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002129 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002130 }
2131};
2132
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002133class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2134 public:
2135 WriteMethodInfoVisitor(OatWriter* writer,
2136 OutputStream* out,
2137 const size_t file_offset,
2138 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002139 : OatDexMethodVisitor(writer, relative_offset),
2140 out_(out),
2141 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002142
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002143 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002144 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2145 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2146
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002147 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002148 size_t file_offset = file_offset_;
2149 OutputStream* out = out_;
2150 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2151 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2152 ++method_offsets_index_;
2153 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2154 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2155 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2156 << dex_file_->PrettyMethod(it.GetMemberIndex());
2157 if (map_offset != 0u) {
2158 // Transform map_offset to actual oat data offset.
2159 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2160 DCHECK_NE(map_offset, 0u);
2161 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2162
2163 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2164 size_t map_size = map.size() * sizeof(map[0]);
2165 if (map_offset == offset_) {
2166 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2167 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2168 ReportWriteFailure(it);
2169 return false;
2170 }
2171 offset_ += map_size;
2172 }
2173 }
2174 DCHECK_OFFSET_();
2175 }
2176
2177 return true;
2178 }
2179
2180 private:
2181 OutputStream* const out_;
2182 size_t const file_offset_;
2183
2184 void ReportWriteFailure(const ClassDataItemIterator& it) {
2185 PLOG(ERROR) << "Failed to write map for "
2186 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2187 }
2188};
2189
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002190// Visit all methods from all classes in all dex files with the specified visitor.
2191bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2192 for (const DexFile* dex_file : *dex_files_) {
2193 const size_t class_def_count = dex_file->NumClassDefs();
2194 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2195 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2196 return false;
2197 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002198 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002199 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2200 const uint8_t* class_data = dex_file->GetClassData(class_def);
2201 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2202 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002203 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002204 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002205 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002206 if (!visitor->VisitMethod(class_def_method_index, it)) {
2207 return false;
2208 }
2209 ++class_def_method_index;
2210 it.Next();
2211 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002212 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002213 }
2214 }
2215 if (UNLIKELY(!visitor->EndClass())) {
2216 return false;
2217 }
2218 }
2219 }
2220 return true;
2221}
2222
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002223size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2224 const InstructionSetFeatures* instruction_set_features,
2225 uint32_t num_dex_files,
2226 SafeMap<std::string, std::string>* key_value_store) {
2227 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2228 oat_header_.reset(OatHeader::Create(instruction_set,
2229 instruction_set_features,
2230 num_dex_files,
2231 key_value_store));
2232 size_oat_header_ += sizeof(OatHeader);
2233 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002234 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002235}
2236
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002237size_t OatWriter::InitClassOffsets(size_t offset) {
2238 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002239 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002240 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2241 if (!oat_dex_file.class_offsets_.empty()) {
2242 // Class offsets are required to be 4 byte aligned.
2243 offset = RoundUp(offset, 4u);
2244 oat_dex_file.class_offsets_offset_ = offset;
2245 offset += oat_dex_file.GetClassOffsetsRawSize();
2246 DCHECK_ALIGNED(offset, 4u);
2247 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002248 }
2249 return offset;
2250}
2251
Brian Carlstrom389efb02012-01-11 12:06:26 -08002252size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002253 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002254 InitOatClassesMethodVisitor visitor(this, offset);
2255 bool success = VisitDexMethods(&visitor);
2256 CHECK(success);
2257 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002258
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002259 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002260 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002261 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2262 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002263 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002264 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002265 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002266 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002267 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002268 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002269
2270 return offset;
2271}
2272
2273size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002274 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002275 return offset;
2276 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002277 {
2278 InitMapMethodVisitor visitor(this, offset);
2279 bool success = VisitDexMethods(&visitor);
2280 DCHECK(success);
2281 offset = visitor.GetOffset();
2282 }
2283 {
2284 InitMethodInfoVisitor visitor(this, offset);
2285 bool success = VisitDexMethods(&visitor);
2286 DCHECK(success);
2287 offset = visitor.GetOffset();
2288 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002289 return offset;
2290}
2291
Vladimir Markof3c52b42017-11-17 17:32:12 +00002292template <typename GetBssOffset>
2293static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2294 size_t slot_size,
2295 const BitVector& indexes,
2296 GetBssOffset get_bss_offset) {
2297 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2298 size_t number_of_entries = 0u;
2299 bool first_index = true;
2300 for (uint32_t index : indexes.Indexes()) {
2301 uint32_t bss_offset = get_bss_offset(index);
2302 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2303 encoder.Reset(index, bss_offset);
2304 ++number_of_entries;
2305 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002306 }
2307 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002308 DCHECK_NE(number_of_entries, 0u);
2309 return number_of_entries;
2310}
2311
2312template <typename GetBssOffset>
2313static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2314 size_t slot_size,
2315 const BitVector& indexes,
2316 GetBssOffset get_bss_offset) {
2317 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2318 slot_size,
2319 indexes,
2320 get_bss_offset);
2321 return IndexBssMapping::ComputeSize(number_of_entries);
2322}
2323
2324size_t OatWriter::InitIndexBssMappings(size_t offset) {
2325 if (bss_method_entry_references_.empty() &&
2326 bss_type_entry_references_.empty() &&
2327 bss_string_entry_references_.empty()) {
2328 return offset;
2329 }
2330 // If there are any classes, the class offsets allocation aligns the offset
2331 // and we cannot have any index bss mappings without class offsets.
2332 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2333 DCHECK_ALIGNED(offset, 4u);
2334
2335 size_t number_of_method_dex_files = 0u;
2336 size_t number_of_type_dex_files = 0u;
2337 size_t number_of_string_dex_files = 0u;
2338 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2339 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2340 const DexFile* dex_file = (*dex_files_)[i];
2341 auto method_it = bss_method_entry_references_.find(dex_file);
2342 if (method_it != bss_method_entry_references_.end()) {
2343 const BitVector& method_indexes = method_it->second;
2344 ++number_of_method_dex_files;
2345 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2346 offset += CalculateIndexBssMappingSize(
2347 dex_file->NumMethodIds(),
2348 static_cast<size_t>(pointer_size),
2349 method_indexes,
2350 [=](uint32_t index) {
2351 return bss_method_entries_.Get({dex_file, index});
2352 });
2353 }
2354
2355 auto type_it = bss_type_entry_references_.find(dex_file);
2356 if (type_it != bss_type_entry_references_.end()) {
2357 const BitVector& type_indexes = type_it->second;
2358 ++number_of_type_dex_files;
2359 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2360 offset += CalculateIndexBssMappingSize(
2361 dex_file->NumTypeIds(),
2362 sizeof(GcRoot<mirror::Class>),
2363 type_indexes,
2364 [=](uint32_t index) {
2365 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2366 });
2367 }
2368
2369 auto string_it = bss_string_entry_references_.find(dex_file);
2370 if (string_it != bss_string_entry_references_.end()) {
2371 const BitVector& string_indexes = string_it->second;
2372 ++number_of_string_dex_files;
2373 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2374 offset += CalculateIndexBssMappingSize(
2375 dex_file->NumStringIds(),
2376 sizeof(GcRoot<mirror::String>),
2377 string_indexes,
2378 [=](uint32_t index) {
2379 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2380 });
2381 }
2382 }
2383 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2384 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2385 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2386 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002387 return offset;
2388}
2389
2390size_t OatWriter::InitOatDexFiles(size_t offset) {
2391 // Initialize offsets of oat dex files.
2392 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2393 oat_dex_file.offset_ = offset;
2394 offset += oat_dex_file.SizeOf();
2395 }
2396 return offset;
2397}
2398
Brian Carlstrome24fa612011-09-29 00:53:55 -07002399size_t OatWriter::InitOatCode(size_t offset) {
2400 // calculate the offsets within OatHeader to executable code
2401 size_t old_offset = offset;
2402 // required to be on a new page boundary
2403 offset = RoundUp(offset, kPageSize);
2404 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002405 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002406 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2407 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2408 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002409 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002410 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002411 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2412 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002413
Vladimir Marko1b404a82017-09-01 13:35:26 +01002414 #define DO_TRAMPOLINE(field, fn_name) \
2415 offset = CompiledCode::AlignCode(offset, instruction_set); \
2416 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2417 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2418 (field) = compiler_driver_->Create ## fn_name(); \
2419 if (generate_debug_info) { \
2420 debug::MethodDebugInfo info = {}; \
2421 info.trampoline_name = #fn_name; \
2422 info.isa = instruction_set; \
2423 info.is_code_address_text_relative = true; \
2424 /* Use the code offset rather than the `adjusted_offset`. */ \
2425 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2426 info.code_size = (field)->size(); \
2427 method_info_.push_back(std::move(info)); \
2428 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002429 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002430
Ian Rogers848871b2013-08-05 10:56:33 -07002431 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002432 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002433 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002434 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2435 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002436
Ian Rogers848871b2013-08-05 10:56:33 -07002437 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002438 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002439 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002440 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002441 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002442 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002443 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002444 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002445 return offset;
2446}
2447
2448size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002449 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002450 if (kOatWriterDebugOatCodeLayout) {
2451 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2452 << this << "), "
2453 << "compilation is disabled";
2454 }
2455
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002456 return offset;
2457 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002458 bool success = false;
2459
2460 {
2461 ScopedObjectAccess soa(Thread::Current());
2462
2463 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2464 success = VisitDexMethods(&layout_code_visitor);
2465 DCHECK(success);
2466
2467 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2468 this,
2469 offset,
2470 layout_code_visitor.ReleaseOrderedMethods());
2471 success = layout_reserve_code_visitor.Visit();
2472 DCHECK(success);
2473 offset = layout_reserve_code_visitor.GetOffset();
2474
2475 // Save the method order because the WriteCodeMethodVisitor will need this
2476 // order again.
2477 DCHECK(ordered_methods_ == nullptr);
2478 ordered_methods_.reset(
2479 new OrderedMethodList(
2480 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2481
2482 if (kOatWriterDebugOatCodeLayout) {
2483 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2484 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2485 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2486 LOG(INFO) << pretty_name
2487 << "@ offset "
2488 << relative_patcher_->GetOffset(ordered_method.method_reference)
2489 << " X hotness "
2490 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2491 }
2492 }
2493 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002494
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002495 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002496 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002497 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002498 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002499 DCHECK(success);
2500 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002501 }
Logan Chien8b977d32012-02-21 19:14:55 +08002502
Brian Carlstrome24fa612011-09-29 00:53:55 -07002503 return offset;
2504}
2505
Vladimir Markoaad75c62016-10-03 08:46:48 +00002506void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002507 {
2508 InitBssLayoutMethodVisitor visitor(this);
2509 bool success = VisitDexMethods(&visitor);
2510 DCHECK(success);
2511 }
2512
2513 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002514 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002515 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002516 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002517 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002518 if (!map_boot_image_tables_to_bss_ &&
2519 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002520 bss_type_entries_.empty() &&
2521 bss_string_entries_.empty()) {
2522 // Nothing to put to the .bss section.
2523 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002524 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002525
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002526 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002527 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002528 if (map_boot_image_tables_to_bss_) {
2529 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2530 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2531 }
2532 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002533
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002534 bss_methods_offset_ = bss_size_;
2535
2536 // Prepare offsets for .bss ArtMethod entries.
2537 for (auto& entry : bss_method_entries_) {
2538 DCHECK_EQ(entry.second, 0u);
2539 entry.second = bss_size_;
2540 bss_size_ += static_cast<size_t>(pointer_size);
2541 }
2542
Vladimir Markoaad75c62016-10-03 08:46:48 +00002543 bss_roots_offset_ = bss_size_;
2544
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002545 // Prepare offsets for .bss Class entries.
2546 for (auto& entry : bss_type_entries_) {
2547 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002548 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002549 bss_size_ += sizeof(GcRoot<mirror::Class>);
2550 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002551 // Prepare offsets for .bss String entries.
2552 for (auto& entry : bss_string_entries_) {
2553 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002554 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002555 bss_size_ += sizeof(GcRoot<mirror::String>);
2556 }
2557}
2558
David Srbeckybc90fd02015-04-22 19:40:27 +01002559bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002560 CHECK(write_state_ == WriteState::kWriteRoData);
2561
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002562 size_t file_offset = oat_data_offset_;
2563 off_t current_offset = out->Seek(0, kSeekCurrent);
2564 if (current_offset == static_cast<off_t>(-1)) {
2565 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2566 }
2567 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2568 size_t relative_offset = current_offset - file_offset;
2569
Vladimir Markoe079e212016-05-25 12:49:49 +01002570 // Wrap out to update checksum with each write.
2571 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2572 out = &checksum_updating_out;
2573
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002574 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2575 if (relative_offset == 0) {
2576 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002577 return false;
2578 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002579
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002580 relative_offset = WriteClasses(out, file_offset, relative_offset);
2581 if (relative_offset == 0) {
2582 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002583 return false;
2584 }
2585
Vladimir Markof3c52b42017-11-17 17:32:12 +00002586 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002587 if (relative_offset == 0) {
2588 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002589 return false;
2590 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002591
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002592 relative_offset = WriteMaps(out, file_offset, relative_offset);
2593 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002594 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2595 return false;
2596 }
2597
2598 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2599 if (relative_offset == 0) {
2600 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002601 return false;
2602 }
2603
David Srbeckybc90fd02015-04-22 19:40:27 +01002604 // Write padding.
2605 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2606 relative_offset += size_executable_offset_alignment_;
2607 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2608 size_t expected_file_offset = file_offset + relative_offset;
2609 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2610 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2611 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2612 return 0;
2613 }
2614 DCHECK_OFFSET();
2615
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002616 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002617 return true;
2618}
2619
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002620class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
2621 public:
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002622 WriteQuickeningInfoMethodVisitor(OatWriter* writer,
2623 OutputStream* out,
2624 uint32_t offset,
2625 SafeMap<const uint8_t*, uint32_t>* offset_map)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002626 : DexMethodVisitor(writer, offset),
2627 out_(out),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002628 written_bytes_(0u),
2629 offset_map_(offset_map) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002630
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002631 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it)
2632 OVERRIDE {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002633 uint32_t method_idx = it.GetMemberIndex();
2634 CompiledMethod* compiled_method =
2635 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
2636
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002637 if (HasQuickeningInfo(compiled_method)) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002638 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002639 // Deduplication is already done on a pointer basis by the compiler driver,
2640 // so we can simply compare the pointers to find out if things are duplicated.
2641 if (offset_map_->find(map.data()) == offset_map_->end()) {
2642 uint32_t length = map.size() * sizeof(map.front());
2643 offset_map_->Put(map.data(), written_bytes_);
2644 if (!out_->WriteFully(&length, sizeof(length)) ||
2645 !out_->WriteFully(map.data(), length)) {
2646 PLOG(ERROR) << "Failed to write quickening info for "
2647 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to "
2648 << out_->GetLocation();
2649 return false;
2650 }
2651 written_bytes_ += sizeof(length) + length;
2652 offset_ += sizeof(length) + length;
2653 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002654 }
2655
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002656 return true;
2657 }
2658
2659 size_t GetNumberOfWrittenBytes() const {
2660 return written_bytes_;
2661 }
2662
2663 private:
2664 OutputStream* const out_;
2665 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002666 // Maps quickening map to its offset in the file.
2667 SafeMap<const uint8_t*, uint32_t>* offset_map_;
2668};
2669
2670class OatWriter::WriteQuickeningIndicesMethodVisitor {
2671 public:
2672 WriteQuickeningIndicesMethodVisitor(OutputStream* out,
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002673 uint32_t quickening_info_bytes,
2674 const SafeMap<const uint8_t*, uint32_t>& offset_map)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002675 : out_(out),
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002676 quickening_info_bytes_(quickening_info_bytes),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002677 written_bytes_(0u),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002678 offset_map_(offset_map) {}
2679
2680 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files, const CompilerDriver& driver) {
2681 for (const DexFile* dex_file : dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002682 const size_t class_def_count = dex_file->NumClassDefs();
2683 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2684 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2685 const uint8_t* class_data = dex_file->GetClassData(class_def);
2686 if (class_data == nullptr) {
2687 continue;
2688 }
2689 for (ClassDataItemIterator class_it(*dex_file, class_data);
2690 class_it.HasNext();
2691 class_it.Next()) {
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002692 if (!class_it.IsAtMethod() || class_it.GetMethodCodeItem() == nullptr) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002693 continue;
2694 }
2695 uint32_t method_idx = class_it.GetMemberIndex();
2696 CompiledMethod* compiled_method =
2697 driver.GetCompiledMethod(MethodReference(dex_file, method_idx));
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002698 const DexFile::CodeItem* code_item = class_it.GetMethodCodeItem();
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08002699 CodeItemDebugInfoAccessor accessor(dex_file, code_item);
2700 const uint32_t existing_debug_info_offset = accessor.DebugInfoOffset();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002701 // If the existing offset is already out of bounds (and not magic marker 0xFFFFFFFF)
2702 // we will pretend the method has been quickened.
2703 bool existing_offset_out_of_bounds =
2704 (existing_debug_info_offset >= dex_file->Size() &&
2705 existing_debug_info_offset != 0xFFFFFFFF);
2706 bool has_quickening_info = HasQuickeningInfo(compiled_method);
2707 if (has_quickening_info || existing_offset_out_of_bounds) {
2708 uint32_t new_debug_info_offset =
2709 dex_file->Size() + quickening_info_bytes_ + written_bytes_;
2710 // Abort if overflow.
2711 CHECK_GE(new_debug_info_offset, dex_file->Size());
2712 const_cast<DexFile::CodeItem*>(code_item)->SetDebugInfoOffset(new_debug_info_offset);
2713 uint32_t quickening_offset = has_quickening_info
2714 ? offset_map_.Get(compiled_method->GetVmapTable().data())
2715 : VdexFile::kNoQuickeningInfoOffset;
2716 if (!out_->WriteFully(&existing_debug_info_offset,
2717 sizeof(existing_debug_info_offset)) ||
2718 !out_->WriteFully(&quickening_offset, sizeof(quickening_offset))) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002719 PLOG(ERROR) << "Failed to write quickening info for "
2720 << dex_file->PrettyMethod(method_idx) << " to "
2721 << out_->GetLocation();
2722 return false;
2723 }
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002724 written_bytes_ += sizeof(existing_debug_info_offset) + sizeof(quickening_offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002725 }
2726 }
2727 }
2728 }
2729 return true;
2730 }
2731
2732 size_t GetNumberOfWrittenBytes() const {
2733 return written_bytes_;
2734 }
2735
2736 private:
2737 OutputStream* const out_;
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002738 const uint32_t quickening_info_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002739 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002740 // Maps quickening map to its offset in the file.
2741 const SafeMap<const uint8_t*, uint32_t>& offset_map_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002742};
2743
2744bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002745 size_t initial_offset = vdex_size_;
2746 size_t start_offset = RoundUp(initial_offset, 4u);
2747
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002748 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2749 if (actual_offset != static_cast<off_t>(start_offset)) {
2750 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2751 << " Expected: " << start_offset
2752 << " Output: " << vdex_out->GetLocation();
2753 return false;
2754 }
2755
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002756 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002757 std::vector<uint32_t> dex_files_indices;
2758 SafeMap<const uint8_t*, uint32_t> offset_map;
2759 WriteQuickeningInfoMethodVisitor visitor1(this, vdex_out, start_offset, &offset_map);
2760 if (!VisitDexMethods(&visitor1)) {
2761 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2762 return false;
2763 }
2764
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002765 if (visitor1.GetNumberOfWrittenBytes() > 0) {
2766 WriteQuickeningIndicesMethodVisitor visitor2(vdex_out,
2767 visitor1.GetNumberOfWrittenBytes(),
2768 offset_map);
2769 if (!visitor2.VisitDexMethods(*dex_files_, *compiler_driver_)) {
2770 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2771 << vdex_out->GetLocation();
2772 return false;
2773 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002774
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002775 if (!vdex_out->Flush()) {
2776 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2777 << " File: " << vdex_out->GetLocation();
2778 return false;
2779 }
2780 size_quickening_info_ = visitor1.GetNumberOfWrittenBytes() +
2781 visitor2.GetNumberOfWrittenBytes();
2782 } else {
2783 // We know we did not quicken.
2784 size_quickening_info_ = 0;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002785 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002786 } else {
2787 // We know we did not quicken.
2788 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002789 }
2790
David Brazdil93592f52017-12-08 10:53:27 +00002791 if (size_quickening_info_ == 0) {
2792 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2793 vdex_quickening_info_offset_ = initial_offset;
2794 size_quickening_info_alignment_ = 0;
2795 } else {
2796 vdex_size_ = start_offset + size_quickening_info_;
2797 vdex_quickening_info_offset_ = start_offset;
2798 size_quickening_info_alignment_ = start_offset - initial_offset;
2799 }
2800
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002801 return true;
2802}
2803
David Brazdil5d5a36b2016-09-14 15:34:10 +01002804bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002805 if (verifier_deps == nullptr) {
2806 // Nothing to write. Record the offset, but no need
2807 // for alignment.
2808 vdex_verifier_deps_offset_ = vdex_size_;
2809 return true;
2810 }
2811
2812 size_t initial_offset = vdex_size_;
2813 size_t start_offset = RoundUp(initial_offset, 4u);
2814
2815 vdex_size_ = start_offset;
2816 vdex_verifier_deps_offset_ = vdex_size_;
2817 size_verifier_deps_alignment_ = start_offset - initial_offset;
2818
2819 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2820 if (actual_offset != static_cast<off_t>(start_offset)) {
2821 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2822 << " Expected: " << start_offset
2823 << " Output: " << vdex_out->GetLocation();
2824 return false;
2825 }
2826
2827 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002828 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002829
2830 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2831 PLOG(ERROR) << "Failed to write verifier deps."
2832 << " File: " << vdex_out->GetLocation();
2833 return false;
2834 }
2835 if (!vdex_out->Flush()) {
2836 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2837 << " File: " << vdex_out->GetLocation();
2838 return false;
2839 }
2840
2841 size_verifier_deps_ = buffer.size();
2842 vdex_size_ += size_verifier_deps_;
2843 return true;
2844}
2845
David Srbeckybc90fd02015-04-22 19:40:27 +01002846bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002847 CHECK(write_state_ == WriteState::kWriteText);
2848
Vladimir Markoe079e212016-05-25 12:49:49 +01002849 // Wrap out to update checksum with each write.
2850 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2851 out = &checksum_updating_out;
2852
Vladimir Marko944da602016-02-19 12:27:55 +00002853 SetMultiOatRelativePatcherAdjustment();
2854
David Srbeckybc90fd02015-04-22 19:40:27 +01002855 const size_t file_offset = oat_data_offset_;
2856 size_t relative_offset = oat_header_->GetExecutableOffset();
2857 DCHECK_OFFSET();
2858
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002859 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002860 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002861 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002862 return false;
2863 }
2864
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002865 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2866 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002867 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002868 return false;
2869 }
2870
Vladimir Markof4da6752014-08-01 19:04:18 +01002871 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002872 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002873 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2874 return false;
2875 }
2876
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002877 if (kIsDebugBuild) {
2878 uint32_t size_total = 0;
2879 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002880 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2881 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002882
David Brazdil7b49e6c2016-09-01 11:06:18 +01002883 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002884 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002885 DO_STAT(size_dex_file_alignment_);
2886 DO_STAT(size_executable_offset_alignment_);
2887 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002888 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002889 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002890 DO_STAT(size_verifier_deps_);
2891 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002892 DO_STAT(size_quickening_info_);
2893 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002894 DO_STAT(size_interpreter_to_interpreter_bridge_);
2895 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2896 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002897 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002898 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002899 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002900 DO_STAT(size_quick_to_interpreter_bridge_);
2901 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002902 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002903 DO_STAT(size_code_);
2904 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002905 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002906 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002907 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002908 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002909 DO_STAT(size_oat_dex_file_location_size_);
2910 DO_STAT(size_oat_dex_file_location_data_);
2911 DO_STAT(size_oat_dex_file_location_checksum_);
2912 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002913 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002914 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002915 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2916 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2917 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002918 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002919 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2920 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002921 DO_STAT(size_oat_lookup_table_alignment_);
2922 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002923 DO_STAT(size_oat_class_offsets_alignment_);
2924 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002925 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002926 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002927 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002928 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002929 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002930 DO_STAT(size_type_bss_mappings_);
2931 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002932 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002933
David Brazdil7b49e6c2016-09-01 11:06:18 +01002934 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2935
2936 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2937 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002938 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002939
David Brazdil7b49e6c2016-09-01 11:06:18 +01002940 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2941 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002942
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002943 write_state_ = WriteState::kWriteHeader;
2944 return true;
2945}
2946
2947bool OatWriter::WriteHeader(OutputStream* out,
2948 uint32_t image_file_location_oat_checksum,
2949 uintptr_t image_file_location_oat_begin,
2950 int32_t image_patch_delta) {
2951 CHECK(write_state_ == WriteState::kWriteHeader);
2952
2953 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2954 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002955 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002956 CHECK_EQ(image_patch_delta, 0);
2957 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2958 } else {
2959 CHECK_ALIGNED(image_patch_delta, kPageSize);
2960 oat_header_->SetImagePatchDelta(image_patch_delta);
2961 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002962 oat_header_->UpdateChecksumWithHeaderData();
2963
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002964 const size_t file_offset = oat_data_offset_;
2965
2966 off_t current_offset = out->Seek(0, kSeekCurrent);
2967 if (current_offset == static_cast<off_t>(-1)) {
2968 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2969 return false;
2970 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002971 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002972 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2973 return false;
2974 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002975 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002976
2977 // Flush all other data before writing the header.
2978 if (!out->Flush()) {
2979 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2980 return false;
2981 }
2982 // Write the header.
2983 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002984 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002985 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2986 return false;
2987 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002988 // Flush the header data.
2989 if (!out->Flush()) {
2990 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002991 return false;
2992 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002993
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002994 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2995 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2996 return false;
2997 }
2998 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2999
3000 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003001 return true;
3002}
3003
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003004size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003005 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3006 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003007 // Class offsets are required to be 4 byte aligned.
3008 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
3009 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
3010 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
3011 return 0u;
3012 }
3013 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00003014 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003015 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003016 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003017 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003018 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003019 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003020 }
3021 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003022 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003023}
3024
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003025size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003026 const bool may_have_compiled = MayHaveCompiledMethods();
3027 if (may_have_compiled) {
3028 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
3029 }
3030 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003031 // If there are any classes, the class offsets allocation aligns the offset.
3032 DCHECK_ALIGNED(relative_offset, 4u);
3033 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003034 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003035 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00003036 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003037 relative_offset += oat_class_headers_[i].SizeOf();
3038 if (may_have_compiled) {
3039 if (!oat_classes_[i].Write(this, out)) {
3040 return 0u;
3041 }
3042 relative_offset += oat_classes_[i].SizeOf();
3043 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003044 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003045 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003046}
3047
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003048size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003049 {
3050 size_t vmap_tables_offset = relative_offset;
3051 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
3052 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3053 return 0;
3054 }
3055 relative_offset = visitor.GetOffset();
3056 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003057 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003058 {
3059 size_t method_infos_offset = relative_offset;
3060 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
3061 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3062 return 0;
3063 }
3064 relative_offset = visitor.GetOffset();
3065 size_method_info_ = relative_offset - method_infos_offset;
3066 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003067
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003068 return relative_offset;
3069}
3070
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003071
Vladimir Markof3c52b42017-11-17 17:32:12 +00003072template <typename GetBssOffset>
3073size_t WriteIndexBssMapping(OutputStream* out,
3074 size_t number_of_indexes,
3075 size_t slot_size,
3076 const BitVector& indexes,
3077 GetBssOffset get_bss_offset) {
3078 // Allocate the IndexBssMapping.
3079 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
3080 number_of_indexes, slot_size, indexes, get_bss_offset);
3081 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
3082 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
3083 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
3084 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
3085 mappings->ClearPadding();
3086 // Encode the IndexBssMapping.
3087 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
3088 auto init_it = mappings->begin();
3089 bool first_index = true;
3090 for (uint32_t index : indexes.Indexes()) {
3091 size_t bss_offset = get_bss_offset(index);
3092 if (first_index) {
3093 first_index = false;
3094 encoder.Reset(index, bss_offset);
3095 } else if (!encoder.TryMerge(index, bss_offset)) {
3096 *init_it = encoder.GetEntry();
3097 ++init_it;
3098 encoder.Reset(index, bss_offset);
3099 }
3100 }
3101 // Store the last entry.
3102 *init_it = encoder.GetEntry();
3103 ++init_it;
3104 DCHECK(init_it == mappings->end());
3105
3106 if (!out->WriteFully(storage.get(), mappings_size)) {
3107 return 0u;
3108 }
3109 return mappings_size;
3110}
3111
3112size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
3113 size_t file_offset,
3114 size_t relative_offset) {
3115 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
3116 if (bss_method_entry_references_.empty() &&
3117 bss_type_entry_references_.empty() &&
3118 bss_string_entry_references_.empty()) {
3119 return relative_offset;
3120 }
3121 // If there are any classes, the class offsets allocation aligns the offset
3122 // and we cannot have method bss mappings without class offsets.
3123 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
3124 "IndexBssMapping alignment check.");
3125 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
3126
3127 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003128 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
3129 const DexFile* dex_file = (*dex_files_)[i];
3130 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00003131 auto method_it = bss_method_entry_references_.find(dex_file);
3132 if (method_it != bss_method_entry_references_.end()) {
3133 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003134 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
3135 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00003136 size_t method_mappings_size = WriteIndexBssMapping(
3137 out,
3138 dex_file->NumMethodIds(),
3139 static_cast<size_t>(pointer_size),
3140 method_indexes,
3141 [=](uint32_t index) {
3142 return bss_method_entries_.Get({dex_file, index});
3143 });
3144 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003145 return 0u;
3146 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003147 size_method_bss_mappings_ += method_mappings_size;
3148 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003149 } else {
3150 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3151 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003152
3153 auto type_it = bss_type_entry_references_.find(dex_file);
3154 if (type_it != bss_type_entry_references_.end()) {
3155 const BitVector& type_indexes = type_it->second;
3156 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3157 DCHECK_OFFSET();
3158 size_t type_mappings_size = WriteIndexBssMapping(
3159 out,
3160 dex_file->NumTypeIds(),
3161 sizeof(GcRoot<mirror::Class>),
3162 type_indexes,
3163 [=](uint32_t index) {
3164 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3165 });
3166 if (type_mappings_size == 0u) {
3167 return 0u;
3168 }
3169 size_type_bss_mappings_ += type_mappings_size;
3170 relative_offset += type_mappings_size;
3171 } else {
3172 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3173 }
3174
3175 auto string_it = bss_string_entry_references_.find(dex_file);
3176 if (string_it != bss_string_entry_references_.end()) {
3177 const BitVector& string_indexes = string_it->second;
3178 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3179 DCHECK_OFFSET();
3180 size_t string_mappings_size = WriteIndexBssMapping(
3181 out,
3182 dex_file->NumStringIds(),
3183 sizeof(GcRoot<mirror::String>),
3184 string_indexes,
3185 [=](uint32_t index) {
3186 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3187 });
3188 if (string_mappings_size == 0u) {
3189 return 0u;
3190 }
3191 size_string_bss_mappings_ += string_mappings_size;
3192 relative_offset += string_mappings_size;
3193 } else {
3194 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3195 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003196 }
3197 return relative_offset;
3198}
3199
3200size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3201 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3202
3203 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3204 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3205 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3206 DCHECK_OFFSET();
3207
3208 // Write OatDexFile.
3209 if (!oat_dex_file->Write(this, out)) {
3210 return 0u;
3211 }
3212 relative_offset += oat_dex_file->SizeOf();
3213 }
3214
3215 return relative_offset;
3216}
3217
3218size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003219 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003220 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003221
Ian Rogers848871b2013-08-05 10:56:33 -07003222 #define DO_TRAMPOLINE(field) \
3223 do { \
3224 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3225 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003226 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003227 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003228 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003229 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003230 return false; \
3231 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003232 size_ ## field += (field)->size(); \
3233 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003234 DCHECK_OFFSET(); \
3235 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003236
Ian Rogers848871b2013-08-05 10:56:33 -07003237 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003238 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003239 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003240 DO_TRAMPOLINE(quick_resolution_trampoline_);
3241 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3242 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003243 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003244 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003245}
3246
Ian Rogers3d504072014-03-01 09:16:49 -08003247size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003248 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003249 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003250 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3251 // As with InitOatCodeDexFiles, also skip the writer if
3252 // compilation was disabled.
3253 if (kOatWriterDebugOatCodeLayout) {
3254 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3255 << this << "), "
3256 << "compilation is disabled";
3257 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003258
Igor Murashkin545412b2017-08-17 15:26:54 -07003259 return relative_offset;
3260 }
3261 ScopedObjectAccess soa(Thread::Current());
3262 DCHECK(ordered_methods_ != nullptr);
3263 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3264 std::move(ordered_methods_);
3265 WriteCodeMethodVisitor visitor(this,
3266 out,
3267 file_offset,
3268 relative_offset,
3269 std::move(*ordered_methods_ptr));
3270 if (UNLIKELY(!visitor.Visit())) {
3271 return 0;
3272 }
3273 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003274
Vladimir Markob163bb72015-03-31 21:49:49 +01003275 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3276 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3277 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3278
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003279 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003280}
3281
Vladimir Marko944da602016-02-19 12:27:55 +00003282bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003283 // Get the elf file offset of the oat file.
3284 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3285 if (raw_file_offset == static_cast<off_t>(-1)) {
3286 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3287 return false;
3288 }
3289 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3290 return true;
3291}
3292
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003293bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003294 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003295
David Brazdil7b49e6c2016-09-01 11:06:18 +01003296 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003297
3298 // Write dex files.
3299 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003300 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003301 return false;
3302 }
3303 }
3304
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003305 CloseSources();
3306 return true;
3307}
3308
3309void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003310 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3311 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3312 }
3313 zipped_dex_files_.clear();
3314 zip_archives_.clear();
3315 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003316}
3317
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003318bool OatWriter::WriteDexFile(OutputStream* out,
3319 File* file,
3320 OatDexFile* oat_dex_file,
3321 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003322 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003323 return false;
3324 }
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003325 // update_input_vdex disables compact dex and layout.
3326 if (!update_input_vdex && (profile_compilation_info_ != nullptr ||
3327 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone)) {
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01003328 CHECK(!update_input_vdex) << "We should never update the input vdex when doing dexlayout";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003329 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3330 return false;
3331 }
3332 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003333 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003334 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003335 return false;
3336 }
3337 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003338 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003339 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003340 return false;
3341 }
3342 } else {
3343 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003344 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003345 return false;
3346 }
3347 }
3348
3349 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003350 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3351 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003352 size_dex_file_ += oat_dex_file->dex_file_size_;
3353 return true;
3354}
3355
3356bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3357 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003358 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003359 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003360 size_t file_offset = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003361 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003362
3363 // Seek to the start of the dex file and flush any pending operations in the stream.
3364 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003365 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3366 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003367 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003368 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003369 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3370 return false;
3371 }
3372 if (!out->Flush()) {
3373 PLOG(ERROR) << "Failed to flush before writing dex file."
3374 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3375 return false;
3376 }
3377 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003378 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003379 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003380 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003381 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3382 return false;
3383 }
3384
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003385 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003386 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003387 return true;
3388}
3389
Jeff Hao608f2ce2016-10-19 11:17:11 -07003390bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3391 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3392 std::string error_msg;
3393 std::string location(oat_dex_file->GetLocation());
3394 std::unique_ptr<const DexFile> dex_file;
3395 if (oat_dex_file->source_.IsZipEntry()) {
3396 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3397 std::unique_ptr<MemMap> mem_map(
3398 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003399 if (mem_map == nullptr) {
3400 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3401 return false;
3402 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003403 dex_file = DexFileLoader::Open(location,
3404 zip_entry->GetCrc32(),
3405 std::move(mem_map),
3406 /* verify */ true,
3407 /* verify_checksum */ true,
3408 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003409 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003410 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003411 int dup_fd = dup(raw_file->Fd());
3412 if (dup_fd < 0) {
3413 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3414 return false;
3415 }
Nicolas Geoffray095c6c92017-10-19 13:59:55 +01003416 dex_file = DexFileLoader::OpenDex(
3417 dup_fd, location, /* verify */ true, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003418 } else {
3419 // The source data is a vdex file.
3420 CHECK(oat_dex_file->source_.IsRawData())
3421 << static_cast<size_t>(oat_dex_file->source_.GetType());
3422 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3423 // Note: The raw data has already been checked to contain the header
3424 // and all the data that the header specifies as the file size.
3425 DCHECK(raw_dex_file != nullptr);
3426 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3427 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3428 // Since the source may have had its layout changed, or may be quickened, don't verify it.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003429 dex_file = DexFileLoader::Open(raw_dex_file,
3430 header->file_size_,
3431 location,
3432 oat_dex_file->dex_file_location_checksum_,
3433 nullptr,
3434 /* verify */ false,
3435 /* verify_checksum */ false,
3436 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003437 }
Jeff Haode197542017-02-03 10:48:13 -08003438 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003439 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003440 return false;
3441 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003442 Options options;
3443 options.output_to_memmap_ = true;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003444 options.compact_dex_level_ = compact_dex_level_;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003445 options.update_checksum_ = true;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003446 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
3447 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
3448 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003449 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3450 // Dex layout can affect the size of the dex file, so we update here what we have set
3451 // when adding the dex file as a source.
3452 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(mem_map->Begin());
3453 oat_dex_file->dex_file_size_ = header->file_size_;
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003454 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003455 return false;
3456 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003457 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003458 return true;
3459}
3460
David Brazdil7b49e6c2016-09-01 11:06:18 +01003461bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003462 File* file,
3463 OatDexFile* oat_dex_file,
3464 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003465 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003466 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003467
3468 // Extract the dex file and get the extracted size.
3469 std::string error_msg;
3470 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3471 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3472 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3473 return false;
3474 }
3475 if (file->Flush() != 0) {
3476 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3477 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3478 return false;
3479 }
3480 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3481 if (extracted_end == static_cast<off_t>(-1)) {
3482 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3483 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3484 return false;
3485 }
3486 if (extracted_end < static_cast<off_t>(start_offset)) {
3487 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3488 << " Start: " << start_offset
3489 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3490 return false;
3491 }
3492 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3493 if (extracted_size < sizeof(DexFile::Header)) {
3494 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3495 << extracted_size << " File: " << oat_dex_file->GetLocation();
3496 return false;
3497 }
3498
3499 // Read the dex file header and extract required data to OatDexFile.
3500 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3501 if (actual_offset != static_cast<off_t>(start_offset)) {
3502 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3503 << " Expected: " << start_offset
3504 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3505 return false;
3506 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003507 if (extracted_size < oat_dex_file->dex_file_size_) {
3508 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3509 << " file size from header: " << oat_dex_file->dex_file_size_
3510 << " File: " << oat_dex_file->GetLocation();
3511 return false;
3512 }
3513
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003514 // Seek both file and stream to the end offset.
3515 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3516 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3517 if (actual_offset != static_cast<off_t>(end_offset)) {
3518 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3519 << " Expected: " << end_offset
3520 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3521 return false;
3522 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003523 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003524 if (actual_offset != static_cast<off_t>(end_offset)) {
3525 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3526 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3527 return false;
3528 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003529 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003530 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3531 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3532 return false;
3533 }
3534
3535 // If we extracted more than the size specified in the header, truncate the file.
3536 if (extracted_size > oat_dex_file->dex_file_size_) {
3537 if (file->SetLength(end_offset) != 0) {
3538 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003539 << " File: " << oat_dex_file->GetLocation()
3540 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003541 return false;
3542 }
3543 }
3544
3545 return true;
3546}
3547
David Brazdil7b49e6c2016-09-01 11:06:18 +01003548bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003549 File* file,
3550 OatDexFile* oat_dex_file,
3551 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003552 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003553 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003554
3555 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3556 if (input_offset != static_cast<off_t>(0)) {
3557 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3558 << " Expected: 0"
3559 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3560 return false;
3561 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003562
3563 // Copy the input dex file using sendfile().
3564 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3565 PLOG(ERROR) << "Failed to copy dex file to oat file."
3566 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3567 return false;
3568 }
3569 if (file->Flush() != 0) {
3570 PLOG(ERROR) << "Failed to flush dex file."
3571 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3572 return false;
3573 }
3574
3575 // Check file position and seek the stream to the end offset.
3576 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3577 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3578 if (actual_offset != static_cast<off_t>(end_offset)) {
3579 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3580 << " Expected: " << end_offset
3581 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3582 return false;
3583 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003584 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003585 if (actual_offset != static_cast<off_t>(end_offset)) {
3586 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3587 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3588 return false;
3589 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003590 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003591 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3592 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3593 return false;
3594 }
3595
3596 return true;
3597}
3598
David Brazdil7b49e6c2016-09-01 11:06:18 +01003599bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003600 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003601 const uint8_t* dex_file,
3602 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003603 // Note: The raw data has already been checked to contain the header
3604 // and all the data that the header specifies as the file size.
3605 DCHECK(dex_file != nullptr);
3606 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3607 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3608
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003609 if (update_input_vdex) {
3610 // The vdex already contains the dex code, no need to write it again.
3611 } else {
3612 if (!out->WriteFully(dex_file, header->file_size_)) {
3613 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3614 << " to " << out->GetLocation();
3615 return false;
3616 }
3617 if (!out->Flush()) {
3618 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3619 << " File: " << oat_dex_file->GetLocation();
3620 return false;
3621 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003622 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003623 return true;
3624}
3625
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003626bool OatWriter::OpenDexFiles(
3627 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003628 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003629 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
3630 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3631 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3632
3633 if (oat_dex_files_.empty()) {
3634 // Nothing to do.
3635 return true;
3636 }
3637
3638 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003639 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003640
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003641 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003642 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3643 length,
3644 PROT_READ | PROT_WRITE,
3645 MAP_SHARED,
3646 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003647 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003648 /* low_4gb */ false,
3649 file->GetPath().c_str(),
3650 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003651 if (dex_files_map == nullptr) {
3652 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3653 << " error: " << error_msg;
3654 return false;
3655 }
3656 std::vector<std::unique_ptr<const DexFile>> dex_files;
3657 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003658 const uint8_t* raw_dex_file =
3659 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003660
3661 if (kIsDebugBuild) {
3662 // Sanity check our input files.
3663 // Note that ValidateDexFileHeader() logs error messages.
3664 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3665 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003666 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3667 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003668
3669 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3670 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3671 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003672 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3673 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003674 }
3675
3676 // Now, open the dex file.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003677 dex_files.emplace_back(DexFileLoader::Open(raw_dex_file,
3678 oat_dex_file.dex_file_size_,
3679 oat_dex_file.GetLocation(),
3680 oat_dex_file.dex_file_location_checksum_,
3681 /* oat_dex_file */ nullptr,
3682 verify,
3683 verify,
3684 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003685 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003686 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3687 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003688 return false;
3689 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003690
3691 // Set the class_offsets size now that we have easy access to the DexFile and
3692 // it has been verified in DexFileLoader::Open.
3693 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003694 }
3695
3696 *opened_dex_files_map = std::move(dex_files_map);
3697 *opened_dex_files = std::move(dex_files);
3698 return true;
3699}
3700
3701bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003702 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003703 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3704 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3705
David Brazdil7b49e6c2016-09-01 11:06:18 +01003706 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3707 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3708 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3709 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3710 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3711 return false;
3712 }
3713
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003714 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3715 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3716 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003717 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3718
3719 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3720 oat_dex_file->class_offsets_.empty()) {
3721 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003722 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003723
3724 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3725 if (table_size == 0u) {
3726 continue;
3727 }
3728
3729 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003730 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003731 const DexFile& dex_file = *opened_dex_files[i];
3732 {
3733 std::unique_ptr<TypeLookupTable> type_lookup_table =
3734 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3735 type_lookup_table_oat_dex_files_.push_back(
3736 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3737 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3738 }
3739 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003740
3741 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003742 size_t initial_offset = oat_size_;
3743 size_t rodata_offset = RoundUp(initial_offset, 4);
3744 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003745
3746 if (padding_size != 0u) {
3747 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003748 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003749 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3750 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003751 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003752 return false;
3753 }
3754 }
3755
3756 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003757 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003758 DCHECK_EQ(table_size, table->RawDataLength());
3759
David Brazdil7b49e6c2016-09-01 11:06:18 +01003760 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003761 PLOG(ERROR) << "Failed to write lookup table."
3762 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003763 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003764 return false;
3765 }
3766
3767 oat_dex_file->lookup_table_offset_ = rodata_offset;
3768
David Brazdil7b49e6c2016-09-01 11:06:18 +01003769 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003770 size_oat_lookup_table_ += table_size;
3771 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003772 }
3773
David Brazdil7b49e6c2016-09-01 11:06:18 +01003774 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003775 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003776 << " File: " << oat_rodata->GetLocation();
3777 return false;
3778 }
3779
3780 return true;
3781}
3782
Mathieu Chartier120aa282017-08-05 16:03:03 -07003783bool OatWriter::WriteDexLayoutSections(
3784 OutputStream* oat_rodata,
3785 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3786 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3787
3788 if (!kWriteDexLayoutInfo) {
3789 return true;;
3790 }
3791
3792 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3793 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3794 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3795 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3796 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3797 return false;
3798 }
3799
3800 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3801 size_t rodata_offset = oat_size_;
3802 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3803 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3804 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3805
3806 // Write dex layout section alignment bytes.
3807 const size_t padding_size =
3808 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3809 if (padding_size != 0u) {
3810 std::vector<uint8_t> buffer(padding_size, 0u);
3811 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3812 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3813 << " File: " << oat_dex_file->GetLocation()
3814 << " Output: " << oat_rodata->GetLocation();
3815 return false;
3816 }
3817 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3818 rodata_offset += padding_size;
3819 }
3820
3821 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3822 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3823 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3824 DCHECK(oat_dex_file != nullptr);
3825 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3826 sizeof(oat_dex_file->dex_sections_layout_))) {
3827 PLOG(ERROR) << "Failed to write dex layout sections."
3828 << " File: " << oat_dex_file->GetLocation()
3829 << " Output: " << oat_rodata->GetLocation();
3830 return false;
3831 }
3832 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3833 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3834 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3835 }
3836 oat_size_ = rodata_offset;
3837
3838 if (!oat_rodata->Flush()) {
3839 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3840 << " File: " << oat_rodata->GetLocation();
3841 return false;
3842 }
3843
3844 return true;
3845}
3846
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003847bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003848 // Write checksums
3849 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
3850 if (actual_offset != sizeof(VdexFile::Header)) {
3851 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3852 << " File: " << vdex_out->GetLocation();
3853 return false;
3854 }
3855
3856 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3857 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3858 if (!vdex_out->WriteFully(
3859 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3860 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3861 << vdex_out->GetLocation();
3862 return false;
3863 }
3864 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3865 }
3866
3867 // Write header.
3868 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003869 if (actual_offset != 0) {
3870 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3871 << " File: " << vdex_out->GetLocation();
3872 return false;
3873 }
3874
David Brazdil5d5a36b2016-09-14 15:34:10 +01003875 DCHECK_NE(vdex_dex_files_offset_, 0u);
3876 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
David Brazdil93592f52017-12-08 10:53:27 +00003877 DCHECK_NE(vdex_quickening_info_offset_, 0u);
David Brazdil5d5a36b2016-09-14 15:34:10 +01003878
3879 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003880 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3881 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003882
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003883 VdexFile::Header vdex_header(oat_dex_files_.size(),
3884 dex_section_size,
3885 verifier_deps_section_size,
3886 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003887 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
3888 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003889 return false;
3890 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003891 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003892
David Brazdil5d5a36b2016-09-14 15:34:10 +01003893 if (!vdex_out->Flush()) {
3894 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3895 << " File: " << vdex_out->GetLocation();
3896 return false;
3897 }
3898
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003899 return true;
3900}
3901
Vladimir Markof4da6752014-08-01 19:04:18 +01003902bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003903 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3904}
3905
3906bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003907 static const uint8_t kPadding[] = {
3908 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3909 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003910 DCHECK_LE(size, sizeof(kPadding));
3911 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003912 return false;
3913 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003914 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01003915 return true;
3916}
3917
Vladimir Marko944da602016-02-19 12:27:55 +00003918void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3919 DCHECK(dex_files_ != nullptr);
3920 DCHECK(relative_patcher_ != nullptr);
3921 DCHECK_NE(oat_data_offset_, 0u);
3922 if (image_writer_ != nullptr && !dex_files_->empty()) {
3923 // The oat data begin may not be initialized yet but the oat file offset is ready.
3924 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3925 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3926 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01003927 }
3928}
3929
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003930OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3931 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003932 CreateTypeLookupTable create_type_lookup_table,
3933 uint32_t dex_file_location_checksum,
3934 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003935 : source_(source),
3936 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003937 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003938 offset_(0),
3939 dex_file_location_size_(strlen(dex_file_location)),
3940 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003941 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003942 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00003943 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003944 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003945 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00003946 type_bss_mapping_offset_(0u),
3947 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00003948 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003949 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07003950}
3951
3952size_t OatWriter::OatDexFile::SizeOf() const {
3953 return sizeof(dex_file_location_size_)
3954 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003955 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08003956 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003957 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003958 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003959 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00003960 + sizeof(type_bss_mapping_offset_)
3961 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003962 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003963}
3964
3965bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3966 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003967 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003968
Vladimir Markoe079e212016-05-25 12:49:49 +01003969 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003970 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003971 return false;
3972 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003973 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003974
Vladimir Markoe079e212016-05-25 12:49:49 +01003975 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003976 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003977 return false;
3978 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003979 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003980
Vladimir Markoe079e212016-05-25 12:49:49 +01003981 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003982 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003983 return false;
3984 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003985 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003986
Vladimir Markoe079e212016-05-25 12:49:49 +01003987 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003988 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003989 return false;
3990 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003991 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003992
Vladimir Markoe079e212016-05-25 12:49:49 +01003993 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003994 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3995 return false;
3996 }
3997 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3998
Vladimir Markoe079e212016-05-25 12:49:49 +01003999 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03004000 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
4001 return false;
4002 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004003 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004004
Mathieu Chartier120aa282017-08-05 16:03:03 -07004005 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4006 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4007 return false;
4008 }
4009 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4010
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004011 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4012 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4013 return false;
4014 }
4015 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4016
Vladimir Markof3c52b42017-11-17 17:32:12 +00004017 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4018 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4019 return false;
4020 }
4021 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4022
4023 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4024 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4025 return false;
4026 }
4027 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4028
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004029 return true;
4030}
4031
4032bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004033 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004034 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4035 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004036 return false;
4037 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004038 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004039 return true;
4040}
4041
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004042OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004043 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004044 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004045 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004046 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004047 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004048
Brian Carlstromba150c32013-08-27 17:31:03 -07004049 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4050
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004051 method_offsets_.resize(compiled_methods_with_code);
4052 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004053
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004054 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4055 // We only create this instance if there are at least some compiled.
4056 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004057 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004058 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4059 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4060 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4061 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004062 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004063 method_bitmap_size_ = 0;
4064 }
4065
4066 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004067 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004068 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004069 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4070 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004071 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004072 method_bitmap_->SetBit(i);
4073 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004074 } else {
4075 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004076 }
4077 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004078}
4079
Brian Carlstrom265091e2013-01-30 14:08:26 -08004080size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004081 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004082 + method_bitmap_size_
4083 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004084}
4085
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004086bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4087 OutputStream* out,
4088 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004089 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004090 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004091 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004092 return false;
4093 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004094 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004095
Vladimir Markoe079e212016-05-25 12:49:49 +01004096 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004097 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004098 return false;
4099 }
4100 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004101 return true;
4102}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004103
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004104bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004105 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004106 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004107 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004108 return false;
4109 }
4110 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004111
Vladimir Markoe079e212016-05-25 12:49:49 +01004112 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004113 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004114 return false;
4115 }
4116 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4117 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004118
Vladimir Markoe079e212016-05-25 12:49:49 +01004119 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004120 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004121 return false;
4122 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004123 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004124 return true;
4125}
4126
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004127const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
4128 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004129 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004130 uint32_t utf16_length;
4131 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
4132 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
4133 InternTable::Utf8String string(utf16_length,
4134 utf8_data,
4135 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
4136 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
4137 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
4138 auto it = table.Find(string);
4139 if (it != table.end()) {
4140 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4141 }
4142 }
4143 LOG(FATAL) << "Did not find boot image string " << utf8_data;
4144 UNREACHABLE();
4145}
4146
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004147const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
4148 dex::TypeIndex type_idx)
4149 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
4150 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
4151 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
4152 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
4153 for (const ClassTable::ClassSet& class_set : table->classes_) {
4154 auto it = class_set.Find(pair);
4155 if (it != class_set.end()) {
4156 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4157 }
4158 }
4159 LOG(FATAL) << "Did not find boot image class " << descriptor;
4160 UNREACHABLE();
4161}
4162
Vladimir Marko74527972016-11-29 15:57:32 +00004163} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004164} // namespace art