blob: 01125a178efd847b16d6beb6362b486f4143f550 [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"
David Sehr013fd802018-01-11 22:55:24 -080036#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080037#include "dex/dex_file-inl.h"
38#include "dex/dex_file_loader.h"
39#include "dex/dex_file_types.h"
40#include "dex/standard_dex_file.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000041#include "dex/verification_results.h"
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080042#include "dex_container.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070043#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070044#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000045#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010046#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030048#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010049#include "image_writer.h"
Andreas Gampe3913e482018-01-22 18:58:01 -080050#include "jit/profile_compilation_info.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010051#include "linker/buffered_output_stream.h"
52#include "linker/file_output_stream.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000053#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010054#include "linker/linker_patch.h"
Vladimir Marko944da602016-02-19 12:27:55 +000055#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000056#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/array.h"
58#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010059#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070060#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010061#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070062#include "os.h"
Mathieu Chartier210531f2018-01-12 10:15:51 -080063#include "quicken_info.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070064#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070065#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030066#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010067#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010068#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010069#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000070#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070071
72namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000073namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070074
Vladimir Marko9bdf1082016-01-21 12:15:52 +000075namespace { // anonymous namespace
76
Mathieu Chartier120aa282017-08-05 16:03:03 -070077// If we write dex layout info in the oat file.
78static constexpr bool kWriteDexLayoutInfo = true;
79
Igor Murashkin545412b2017-08-17 15:26:54 -070080// Force the OAT method layout to be sorted-by-name instead of
81// the default (class_def_idx, method_idx).
82//
83// Otherwise if profiles are used, that will act as
84// the primary sort order.
85//
86// A bit easier to use for development since oatdump can easily
87// show that things are being re-ordered when two methods aren't adjacent.
88static constexpr bool kOatWriterForceOatCodeLayout = false;
89
90static constexpr bool kOatWriterDebugOatCodeLayout = false;
91
Vladimir Marko9bdf1082016-01-21 12:15:52 +000092typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
93
94const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
95 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
96}
97
Vladimir Markoe079e212016-05-25 12:49:49 +010098class ChecksumUpdatingOutputStream : public OutputStream {
99 public:
100 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
101 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
102
103 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
104 oat_header_->UpdateChecksum(buffer, byte_count);
105 return out_->WriteFully(buffer, byte_count);
106 }
107
108 off_t Seek(off_t offset, Whence whence) OVERRIDE {
109 return out_->Seek(offset, whence);
110 }
111
112 bool Flush() OVERRIDE {
113 return out_->Flush();
114 }
115
116 private:
117 OutputStream* const out_;
118 OatHeader* const oat_header_;
119};
120
Vladimir Marko0c737df2016-08-01 16:33:16 +0100121inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
122 // We want to align the code rather than the preheader.
123 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
124 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
125 return aligned_code_offset - unaligned_code_offset;
126}
127
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000128} // anonymous namespace
129
130// Defines the location of the raw dex file to write.
131class OatWriter::DexFileSource {
132 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800133 enum Type {
134 kNone,
135 kZipEntry,
136 kRawFile,
137 kRawData,
138 };
139
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000140 explicit DexFileSource(ZipEntry* zip_entry)
141 : type_(kZipEntry), source_(zip_entry) {
142 DCHECK(source_ != nullptr);
143 }
144
145 explicit DexFileSource(File* raw_file)
146 : type_(kRawFile), source_(raw_file) {
147 DCHECK(source_ != nullptr);
148 }
149
150 explicit DexFileSource(const uint8_t* dex_file)
151 : type_(kRawData), source_(dex_file) {
152 DCHECK(source_ != nullptr);
153 }
154
Mathieu Chartier497d5262017-02-28 20:17:30 -0800155 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000156 bool IsZipEntry() const { return type_ == kZipEntry; }
157 bool IsRawFile() const { return type_ == kRawFile; }
158 bool IsRawData() const { return type_ == kRawData; }
159
160 ZipEntry* GetZipEntry() const {
161 DCHECK(IsZipEntry());
162 DCHECK(source_ != nullptr);
163 return static_cast<ZipEntry*>(const_cast<void*>(source_));
164 }
165
166 File* GetRawFile() const {
167 DCHECK(IsRawFile());
168 DCHECK(source_ != nullptr);
169 return static_cast<File*>(const_cast<void*>(source_));
170 }
171
172 const uint8_t* GetRawData() const {
173 DCHECK(IsRawData());
174 DCHECK(source_ != nullptr);
175 return static_cast<const uint8_t*>(source_);
176 }
177
178 void Clear() {
179 type_ = kNone;
180 source_ = nullptr;
181 }
182
183 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000184 Type type_;
185 const void* source_;
186};
187
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700188// OatClassHeader is the header only part of the oat class that is required even when compilation
189// is not enabled.
190class OatWriter::OatClassHeader {
191 public:
192 OatClassHeader(uint32_t offset,
193 uint32_t num_non_null_compiled_methods,
194 uint32_t num_methods,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000195 ClassStatus status)
196 : status_(enum_cast<uint16_t>(status)),
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700197 offset_(offset) {
198 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
199 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
200 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
201 if (num_non_null_compiled_methods == 0) {
202 type_ = kOatClassNoneCompiled;
203 } else if (num_non_null_compiled_methods == num_methods) {
204 type_ = kOatClassAllCompiled;
205 } else {
206 type_ = kOatClassSomeCompiled;
207 }
208 }
209
210 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
211
212 static size_t SizeOf() {
213 return sizeof(status_) + sizeof(type_);
214 }
215
216 // Data to write.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000217 static_assert(enum_cast<>(ClassStatus::kLast) < (1 << 16), "class status won't fit in 16bits");
218 uint16_t status_;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700219
220 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
221 uint16_t type_;
222
223 // Offset of start of OatClass from beginning of OatHeader. It is
224 // used to validate file position when writing.
225 uint32_t offset_;
226};
227
228// The actual oat class body contains the information about compiled methods. It is only required
229// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000230class OatWriter::OatClass {
231 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700232 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100233 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700234 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000235 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700237 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000238
239 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
240 return compiled_methods_[class_def_method_index];
241 }
242
Vladimir Marko49b0f452015-12-10 13:49:19 +0000243 // CompiledMethods for each class_def_method_index, or null if no method is available.
244 dchecked_vector<CompiledMethod*> compiled_methods_;
245
246 // Offset from OatClass::offset_ to the OatMethodOffsets for the
247 // class_def_method_index. If 0, it means the corresponding
248 // CompiledMethod entry in OatClass::compiled_methods_ should be
249 // null and that the OatClass::type_ should be kOatClassBitmap.
250 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
251
252 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000253 uint32_t method_bitmap_size_;
254
255 // bit vector indexed by ClassDef method index. When
256 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
257 // method has an OatMethodOffsets in methods_offsets_, otherwise
258 // the entry was ommited to save space. If OatClassType::type_ is
259 // not is kOatClassBitmap, the bitmap will be null.
260 std::unique_ptr<BitVector> method_bitmap_;
261
262 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
263 // present in the OatClass. Note that some may be missing if
264 // OatClass::compiled_methods_ contains null values (and
265 // oat_method_offsets_offsets_from_oat_class_ should contain 0
266 // values in this case).
267 dchecked_vector<OatMethodOffsets> method_offsets_;
268 dchecked_vector<OatQuickMethodHeader> method_headers_;
269
270 private:
271 size_t GetMethodOffsetsRawSize() const {
272 return method_offsets_.size() * sizeof(method_offsets_[0]);
273 }
274
275 DISALLOW_COPY_AND_ASSIGN(OatClass);
276};
277
278class OatWriter::OatDexFile {
279 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000280 OatDexFile(const char* dex_file_location,
281 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000282 CreateTypeLookupTable create_type_lookup_table,
283 uint32_t dex_file_location_checksun,
284 size_t dex_file_size);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000285 OatDexFile(OatDexFile&& src) = default;
286
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000287 const char* GetLocation() const {
288 return dex_file_location_data_;
289 }
290
Vladimir Marko49b0f452015-12-10 13:49:19 +0000291 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000292 bool Write(OatWriter* oat_writer, OutputStream* out) const;
293 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
294
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100295 size_t GetClassOffsetsRawSize() const {
296 return class_offsets_.size() * sizeof(class_offsets_[0]);
297 }
298
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000299 // The source of the dex file.
300 DexFileSource source_;
301
302 // Whether to create the type lookup table.
303 CreateTypeLookupTable create_type_lookup_table_;
304
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000305 // Dex file size. Passed in the constructor, but could be
306 // overwritten by LayoutAndWriteDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000307 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000308
309 // Offset of start of OatDexFile from beginning of OatHeader. It is
310 // used to validate file position when writing.
311 size_t offset_;
312
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000313 ///// Start of data to write to vdex/oat file.
314
315 const uint32_t dex_file_location_size_;
316 const char* const dex_file_location_data_;
317
318 // The checksum of the dex file.
319 const uint32_t dex_file_location_checksum_;
320
321 // Offset of the dex file in the vdex file. Set when writing dex files in
322 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000323 uint32_t dex_file_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000324
325 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000326 uint32_t lookup_table_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000327
328 // Class and BSS offsets set in PrepareLayout.
329 uint32_t class_offsets_offset_;
Nicolas Geoffray715d6722017-11-20 22:28:46 +0000330 uint32_t method_bss_mapping_offset_;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000331 uint32_t type_bss_mapping_offset_;
332 uint32_t string_bss_mapping_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000333
334 // Offset of dex sections that will have different runtime madvise states.
335 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700336 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000337
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000338 // Data to write to a separate section. We set the length
339 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000340 dchecked_vector<uint32_t> class_offsets_;
341
Mathieu Chartier120aa282017-08-05 16:03:03 -0700342 // Dex section layout info to serialize.
343 DexLayoutSections dex_sections_layout_;
344
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000345 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000346 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000347 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
348};
349
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100350#define DCHECK_OFFSET() \
351 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
352 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
353
354#define DCHECK_OFFSET_() \
355 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
356 << "file_offset=" << file_offset << " offset_=" << offset_
357
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700358OatWriter::OatWriter(bool compiling_boot_image,
359 TimingLogger* timings,
360 ProfileCompilationInfo* info,
361 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000362 : write_state_(WriteState::kAddingDexFileSources),
363 timings_(timings),
364 raw_dex_files_(),
365 zip_archives_(),
366 zipped_dex_files_(),
367 zipped_dex_file_locations_(),
368 compiler_driver_(nullptr),
369 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800370 compiling_boot_image_(compiling_boot_image),
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000371 only_contains_uncompressed_zip_entries_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000372 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100373 vdex_size_(0u),
374 vdex_dex_files_offset_(0u),
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800375 vdex_dex_shared_data_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100376 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100377 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100378 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000379 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000380 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100381 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000382 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100383 bss_method_entry_references_(),
384 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000385 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000386 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100387 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100388 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700389 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100390 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000391 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700392 size_dex_file_alignment_(0),
393 size_executable_offset_alignment_(0),
394 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700395 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700396 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100397 size_verifier_deps_(0),
398 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100399 size_quickening_info_(0),
400 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700401 size_interpreter_to_interpreter_bridge_(0),
402 size_interpreter_to_compiled_code_bridge_(0),
403 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800404 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700405 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700406 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700407 size_quick_to_interpreter_bridge_(0),
408 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100409 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700410 size_code_(0),
411 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100412 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100413 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700414 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700415 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700416 size_oat_dex_file_location_size_(0),
417 size_oat_dex_file_location_data_(0),
418 size_oat_dex_file_location_checksum_(0),
419 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000420 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000421 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700422 size_oat_dex_file_dex_layout_sections_offset_(0),
423 size_oat_dex_file_dex_layout_sections_(0),
424 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100425 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000426 size_oat_dex_file_type_bss_mapping_offset_(0),
427 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000428 size_oat_lookup_table_alignment_(0),
429 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000430 size_oat_class_offsets_alignment_(0),
431 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700432 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700433 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700434 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100435 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100436 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000437 size_type_bss_mappings_(0u),
438 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000439 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700440 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700441 profile_compilation_info_(info),
442 compact_dex_level_(compact_dex_level) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000443}
444
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000445static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
446 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
447 if (!valid_standard_dex_magic) {
448 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
449 return false;
450 }
451 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
452 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
453 return false;
454 }
455 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
456 if (header->file_size_ < sizeof(DexFile::Header)) {
457 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
458 << " File: " << location;
459 return false;
460 }
461 return true;
462}
463
464static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
465 uint8_t* raw_header,
466 const char* location) {
467 // Read the dex file header and perform minimal verification.
468 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
469 PLOG(ERROR) << "Failed to read dex file header. Actual: "
470 << " File: " << location << " Output: " << file->GetPath();
471 return nullptr;
472 }
473 if (!ValidateDexFileHeader(raw_header, location)) {
474 return nullptr;
475 }
476
477 return AsUnalignedDexFileHeader(raw_header);
478}
479
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480bool OatWriter::AddDexFileSource(const char* filename,
481 const char* location,
482 CreateTypeLookupTable create_type_lookup_table) {
483 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
484 uint32_t magic;
485 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700486 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
487 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
489 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700490 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000491 uint8_t raw_header[sizeof(DexFile::Header)];
492 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
493 if (header == nullptr) {
494 return false;
495 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000496 // The file is open for reading, not writing, so it's OK to let the File destructor
497 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700498 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000499 oat_dex_files_.emplace_back(/* OatDexFile */
500 location,
501 DexFileSource(raw_dex_files_.back().get()),
502 create_type_lookup_table,
503 header->checksum_,
504 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000505 } else if (IsZipMagic(magic)) {
506 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
507 return false;
508 }
509 } else {
510 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
511 return false;
512 }
513 return true;
514}
515
516// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700517bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000518 const char* location,
519 CreateTypeLookupTable create_type_lookup_table) {
520 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
521 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700522 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000523 ZipArchive* zip_archive = zip_archives_.back().get();
524 if (zip_archive == nullptr) {
525 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
526 << error_msg;
527 return false;
528 }
529 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700530 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000531 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
532 if (entry == nullptr) {
533 break;
534 }
535 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700536 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000537 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000538 // We override the checksum from header with the CRC from ZIP entry.
539 oat_dex_files_.emplace_back(/* OatDexFile */
540 full_location,
541 DexFileSource(zipped_dex_files_.back().get()),
542 create_type_lookup_table,
543 zipped_dex_files_.back()->GetCrc32(),
544 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000545 }
546 if (zipped_dex_file_locations_.empty()) {
547 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
548 return false;
549 }
550 return true;
551}
552
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000553// Add dex file source(s) from a vdex file specified by a file handle.
554bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
555 const char* location,
556 CreateTypeLookupTable create_type_lookup_table) {
557 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
558 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000559 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000560 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
561 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000562 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
563 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000564 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700565
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700566 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000567 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
568 return false;
569 }
570 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700571 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000572 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000573 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
574 oat_dex_files_.emplace_back(/* OatDexFile */
575 full_location,
576 DexFileSource(current_dex_data),
577 create_type_lookup_table,
578 vdex_file.GetLocationChecksum(i),
579 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000580 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000581
582 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
583 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
584 return false;
585 }
586
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000587 if (oat_dex_files_.empty()) {
588 LOG(ERROR) << "No dex files in vdex file created from " << location;
589 return false;
590 }
591 return true;
592}
593
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000594// Add dex file source from raw memory.
595bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
596 const char* location,
597 uint32_t location_checksum,
598 CreateTypeLookupTable create_type_lookup_table) {
599 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
600 if (data.size() < sizeof(DexFile::Header)) {
601 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
602 << data.size() << " File: " << location;
603 return false;
604 }
605 if (!ValidateDexFileHeader(data.data(), location)) {
606 return false;
607 }
608 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
609 if (data.size() < header->file_size_) {
610 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
611 << " file size from header: " << header->file_size_ << " File: " << location;
612 return false;
613 }
614
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000615 oat_dex_files_.emplace_back(/* OatDexFile */
616 location,
617 DexFileSource(data.data()),
618 create_type_lookup_table,
619 location_checksum,
620 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000621 return true;
622}
623
Calin Juravle1ce70852017-06-28 10:59:03 -0700624dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
625 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000626 locations.reserve(oat_dex_files_.size());
627 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
628 locations.push_back(oat_dex_file.GetLocation());
629 }
630 return locations;
631}
632
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700633bool OatWriter::MayHaveCompiledMethods() const {
634 return CompilerFilter::IsAnyCompilationEnabled(
635 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
636}
637
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000638bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100639 File* vdex_file,
640 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000641 InstructionSet instruction_set,
642 const InstructionSetFeatures* instruction_set_features,
643 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800644 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000645 bool update_input_vdex,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000646 /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000647 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
648 CHECK(write_state_ == WriteState::kAddingDexFileSources);
649
David Brazdil7b49e6c2016-09-01 11:06:18 +0100650 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
651 if (!RecordOatDataOffset(oat_rodata)) {
652 return false;
653 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000654
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000655 std::vector<std::unique_ptr<MemMap>> dex_files_map;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000656 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100657
658 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000659
660 // Reserve space for Vdex header and checksums.
661 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100662 oat_size_ = InitOatHeader(instruction_set,
663 instruction_set_features,
664 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
665 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100666
667 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
668
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000669 std::unique_ptr<BufferedOutputStream> vdex_out =
670 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
671 // Write DEX files into VDEX, mmap and open them.
672 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
673 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
674 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000675 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000676
Mathieu Chartier120aa282017-08-05 16:03:03 -0700677 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000678 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
679 return false;
680 }
681
Mathieu Chartier120aa282017-08-05 16:03:03 -0700682 // Write dex layout sections into the oat file.
683 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
684 return false;
685 }
686
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000687 *opened_dex_files_map = std::move(dex_files_map);
688 *opened_dex_files = std::move(dex_files);
689 write_state_ = WriteState::kPrepareLayout;
690 return true;
691}
692
Vladimir Marko74527972016-11-29 15:57:32 +0000693void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000694 CHECK(write_state_ == WriteState::kPrepareLayout);
695
Vladimir Marko944da602016-02-19 12:27:55 +0000696 relative_patcher_ = relative_patcher;
697 SetMultiOatRelativePatcherAdjustment();
698
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000699 if (compiling_boot_image_) {
700 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800701 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100702 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000703 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100704
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100705 {
706 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
707 InitBssLayout(instruction_set);
708 }
709
David Brazdil7b49e6c2016-09-01 11:06:18 +0100710 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800711 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100712 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
713 offset = InitClassOffsets(offset);
714 }
715 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000716 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800717 offset = InitOatClasses(offset);
718 }
719 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000720 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
721 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100722 }
723 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000724 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100725 offset = InitOatMaps(offset);
726 }
727 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100728 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
729 oat_header_->SetOatDexFilesOffset(offset);
730 offset = InitOatDexFiles(offset);
731 }
732 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000733 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800734 offset = InitOatCode(offset);
735 }
736 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000737 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800738 offset = InitOatCodeDexFiles(offset);
739 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100740 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100741 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100742
Brian Carlstrome24fa612011-09-29 00:53:55 -0700743 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800744 if (compiling_boot_image_) {
745 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000746 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800747 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000748
749 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700750}
751
Ian Rogers0571d352011-11-03 19:51:38 -0700752OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700753}
754
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755class OatWriter::DexMethodVisitor {
756 public:
757 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100758 : writer_(writer),
759 offset_(offset),
760 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700761 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100762
763 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
764 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700765 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100766 dex_file_ = dex_file;
767 class_def_index_ = class_def_index;
768 return true;
769 }
770
771 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
772
773 virtual bool EndClass() {
774 if (kIsDebugBuild) {
775 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700776 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100777 }
778 return true;
779 }
780
781 size_t GetOffset() const {
782 return offset_;
783 }
784
785 protected:
786 virtual ~DexMethodVisitor() { }
787
788 OatWriter* const writer_;
789
790 // The offset is usually advanced for each visited method by the derived class.
791 size_t offset_;
792
793 // The dex file and class def index are set in StartClass().
794 const DexFile* dex_file_;
795 size_t class_def_index_;
796};
797
798class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
799 public:
800 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100801 : DexMethodVisitor(writer, offset),
802 oat_class_index_(0u),
803 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100804
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100805 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700807 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
808 // There are no oat classes if there aren't any compiled methods.
809 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
810 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100811 method_offsets_index_ = 0u;
812 return true;
813 }
814
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100815 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100816 ++oat_class_index_;
817 return DexMethodVisitor::EndClass();
818 }
819
820 protected:
821 size_t oat_class_index_;
822 size_t method_offsets_index_;
823};
824
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100825static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000826 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100827}
828
829static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000830 // The dextodexcompiler puts the quickening info table into the CompiledMethod
831 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100832 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
833}
834
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100835class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
836 public:
837 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
838 : DexMethodVisitor(writer, /* offset */ 0u) {}
839
840 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
841 const ClassDataItemIterator& it) OVERRIDE {
842 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
843 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
844 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100845 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100846 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
847 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
848 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000849 AddBssReference(target_method,
850 target_method.dex_file->NumMethodIds(),
851 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100852 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
853 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000854 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
855 AddBssReference(target_type,
856 target_type.dex_file->NumTypeIds(),
857 &writer_->bss_type_entry_references_);
858 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100859 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000860 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
861 AddBssReference(target_string,
862 target_string.dex_file->NumStringIds(),
863 &writer_->bss_string_entry_references_);
864 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100865 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
866 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100867 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100868 }
869 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100870 } else {
871 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100872 }
873 return true;
874 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000875
876 private:
877 void AddBssReference(const DexFileReference& ref,
878 size_t number_of_indexes,
879 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
880 // We currently support inlining of throwing instructions only when they originate in the
881 // same dex file as the outer method. All .bss references are used by throwing instructions.
882 DCHECK_EQ(dex_file_, ref.dex_file);
883
884 auto refs_it = references->find(ref.dex_file);
885 if (refs_it == references->end()) {
886 refs_it = references->Put(
887 ref.dex_file,
888 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
889 refs_it->second.ClearAllBits();
890 }
891 refs_it->second.SetBit(ref.index);
892 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100893};
894
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100895class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
896 public:
897 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100898 : DexMethodVisitor(writer, offset),
899 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100900 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000901 size_t num_classes = 0u;
902 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
903 num_classes += oat_dex_file.class_offsets_.size();
904 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700905 // If we aren't compiling only reserve headers.
906 writer_->oat_class_headers_.reserve(num_classes);
907 if (writer->MayHaveCompiledMethods()) {
908 writer->oat_classes_.reserve(num_classes);
909 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100910 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100911 // If there are any classes, the class offsets allocation aligns the offset.
912 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100913 }
914
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100915 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100916 DexMethodVisitor::StartClass(dex_file, class_def_index);
917 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100918 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100919 return true;
920 }
921
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300922 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100923 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100924 // Fill in the compiled_methods_ array for methods that have a
925 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100926 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100927 // OatMethodOffsets for the compiled methods.
928 uint32_t method_idx = it.GetMemberIndex();
929 CompiledMethod* compiled_method =
930 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
931 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100932 if (HasCompiledCode(compiled_method)) {
933 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100934 }
935 return true;
936 }
937
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100938 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko2c64a832018-01-04 11:31:56 +0000940 ClassStatus status;
Andreas Gampebb846102017-05-11 21:03:35 -0700941 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
942 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700943 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
944 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700945 // The oat class status is used only for verification of resolved classes,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000946 // so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
Andreas Gampebb846102017-05-11 21:03:35 -0700947 // during compile-time verification.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000948 status = ClassStatus::kErrorResolved;
Andreas Gampebb846102017-05-11 21:03:35 -0700949 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +0000950 status = ClassStatus::kNotReady;
Andreas Gampebb846102017-05-11 21:03:35 -0700951 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952 }
953
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700954 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100955 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700956 compiled_methods_.size(),
957 status);
958 OatClassHeader& header = writer_->oat_class_headers_.back();
959 offset_ += header.SizeOf();
960 if (writer_->MayHaveCompiledMethods()) {
961 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100962 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700963 header.type_);
964 offset_ += writer_->oat_classes_.back().SizeOf();
965 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100966 return DexMethodVisitor::EndClass();
967 }
968
969 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000970 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100971 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100972};
973
Igor Murashkin545412b2017-08-17 15:26:54 -0700974// CompiledMethod + metadata required to do ordered method layout.
975//
976// See also OrderedMethodVisitor.
977struct OatWriter::OrderedMethodData {
978 ProfileCompilationInfo::MethodHotness method_hotness;
979 OatClass* oat_class;
980 CompiledMethod* compiled_method;
981 MethodReference method_reference;
982 size_t method_offsets_index;
983
984 size_t class_def_index;
985 uint32_t access_flags;
986 const DexFile::CodeItem* code_item;
987
988 // A value of -1 denotes missing debug info
989 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
990 // Index into writer_->method_info_
991 size_t debug_info_idx;
992
993 bool HasDebugInfo() const {
994 return debug_info_idx != kDebugInfoIdxInvalid;
995 }
996
997 // Bin each method according to the profile flags.
998 //
999 // Groups by e.g.
1000 // -- not hot at all
1001 // -- hot
1002 // -- hot and startup
1003 // -- hot and post-startup
1004 // -- hot and startup and poststartup
1005 // -- startup
1006 // -- startup and post-startup
1007 // -- post-startup
1008 //
1009 // (See MethodHotness enum definition for up-to-date binning order.)
1010 bool operator<(const OrderedMethodData& other) const {
1011 if (kOatWriterForceOatCodeLayout) {
1012 // Development flag: Override default behavior by sorting by name.
1013
1014 std::string name = method_reference.PrettyMethod();
1015 std::string other_name = other.method_reference.PrettyMethod();
1016 return name < other_name;
1017 }
1018
1019 // Use the profile's method hotness to determine sort order.
1020 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1021 return true;
1022 }
1023
1024 // Default: retain the original order.
1025 return false;
1026 }
1027
1028 private:
1029 // Used to determine relative order for OAT code layout when determining
1030 // binning.
1031 size_t GetMethodHotnessOrder() const {
1032 bool hotness[] = {
1033 method_hotness.IsHot(),
1034 method_hotness.IsStartup(),
1035 method_hotness.IsPostStartup()
1036 };
1037
1038
1039 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1040 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1041 // time that memory is referenced in the process.
1042
1043 size_t hotness_bits = 0;
1044 for (size_t i = 0; i < arraysize(hotness); ++i) {
1045 if (hotness[i]) {
1046 hotness_bits |= (1 << i);
1047 }
1048 }
1049
1050 if (kIsDebugBuild) {
1051 // Check for bins that are always-empty given a real profile.
1052 if (method_hotness.IsHot() &&
1053 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1054 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001055 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1056 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001057 // This is not fatal, so only warn.
1058 }
1059 }
1060
1061 return hotness_bits;
1062 }
1063};
1064
1065// Given a queue of CompiledMethod in some total order,
1066// visit each one in that order.
1067class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001068 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001069 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1070 : ordered_methods_(std::move(ordered_methods)) {
1071 }
1072
1073 virtual ~OrderedMethodVisitor() {}
1074
1075 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1076 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1077 if (!VisitStart()) {
1078 return false;
1079 }
1080
1081 for (const OrderedMethodData& method_data : ordered_methods_) {
1082 if (!VisitMethod(method_data)) {
1083 return false;
1084 }
1085 }
1086
1087 return VisitComplete();
1088 }
1089
1090 // Invoked once at the beginning, prior to visiting anything else.
1091 //
1092 // Return false to abort further visiting.
1093 virtual bool VisitStart() { return true; }
1094
1095 // Invoked repeatedly in the order specified by `ordered_methods`.
1096 //
1097 // Return false to short-circuit and to stop visiting further methods.
1098 virtual bool VisitMethod(const OrderedMethodData& method_data)
1099 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1100
1101 // Invoked once at the end, after every other method has been successfully visited.
1102 //
1103 // Return false to indicate the overall `Visit` has failed.
1104 virtual bool VisitComplete() = 0;
1105
1106 OrderedMethodList ReleaseOrderedMethods() {
1107 return std::move(ordered_methods_);
1108 }
1109
1110 private:
1111 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1112 // Methods can be inserted more than once in case of duplicated methods.
1113 OrderedMethodList ordered_methods_;
1114};
1115
1116// Visit every compiled method in order to determine its order within the OAT file.
1117// Methods from the same class do not need to be adjacent in the OAT code.
1118class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1119 public:
1120 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1121 : OatDexMethodVisitor(writer, offset) {
1122 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001123
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001124 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001125 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001126 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001127 }
1128
Igor Murashkin545412b2017-08-17 15:26:54 -07001129 bool VisitMethod(size_t class_def_method_index,
1130 const ClassDataItemIterator& it)
1131 OVERRIDE
1132 REQUIRES_SHARED(Locks::mutator_lock_) {
1133 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1134
Vladimir Marko49b0f452015-12-10 13:49:19 +00001135 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001136 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1137
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001138 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001139 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001140
Igor Murashkin545412b2017-08-17 15:26:54 -07001141 {
1142 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1143 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1144 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001145
Igor Murashkin545412b2017-08-17 15:26:54 -07001146 // Debug method info must be pushed in the original order
1147 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1148 // ElfCompilationUnitWriter::Write requires this.
1149 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1150 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1151 writer_->method_info_.push_back(info);
1152
1153 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1154 // once we know the offsets.
1155 //
1156 // Store the index into writer_->method_info_ since future push-backs
1157 // could reallocate and change the underlying data address.
1158 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001159 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001160 }
1161
1162 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1163
1164 // Lookup method hotness from profile, if available.
1165 // Otherwise assume a default of none-hotness.
1166 ProfileCompilationInfo::MethodHotness method_hotness =
1167 writer_->profile_compilation_info_ != nullptr
1168 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1169 : ProfileCompilationInfo::MethodHotness();
1170
1171 // Handle duplicate methods by pushing them repeatedly.
1172 OrderedMethodData method_data = {
1173 method_hotness,
1174 oat_class,
1175 compiled_method,
1176 method_ref,
1177 method_offsets_index_,
1178 class_def_index_,
1179 it.GetMethodAccessFlags(),
1180 it.GetMethodCodeItem(),
1181 debug_info_idx
1182 };
1183 ordered_methods_.push_back(method_data);
1184
1185 method_offsets_index_++;
1186 }
1187
1188 return true;
1189 }
1190
1191 OrderedMethodList ReleaseOrderedMethods() {
1192 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1193 // Sort by the method ordering criteria (in OrderedMethodData).
1194 // Since most methods will have the same ordering criteria,
1195 // we preserve the original insertion order within the same sort order.
1196 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1197 } else {
1198 // The profile-less behavior is as if every method had 0 hotness
1199 // associated with it.
1200 //
1201 // Since sorting all methods with hotness=0 should give back the same
1202 // order as before, don't do anything.
1203 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1204 }
1205
1206 return std::move(ordered_methods_);
1207 }
1208
1209 private:
1210 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1211 // Methods can be inserted more than once in case of duplicated methods.
1212 OrderedMethodList ordered_methods_;
1213};
1214
1215// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1216class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1217 public:
1218 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1219 size_t offset,
1220 OrderedMethodList ordered_methods)
1221 : LayoutReserveOffsetCodeMethodVisitor(writer,
1222 offset,
1223 writer->GetCompilerDriver()->GetCompilerOptions(),
1224 std::move(ordered_methods)) {
1225 }
1226
1227 virtual bool VisitComplete() OVERRIDE {
1228 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1229 if (generate_debug_info_) {
1230 std::vector<debug::MethodDebugInfo> thunk_infos =
1231 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1232 writer_->method_info_.insert(writer_->method_info_.end(),
1233 std::make_move_iterator(thunk_infos.begin()),
1234 std::make_move_iterator(thunk_infos.end()));
1235 }
1236 return true;
1237 }
1238
1239 virtual bool VisitMethod(const OrderedMethodData& method_data)
1240 OVERRIDE
1241 REQUIRES_SHARED(Locks::mutator_lock_) {
1242 OatClass* oat_class = method_data.oat_class;
1243 CompiledMethod* compiled_method = method_data.compiled_method;
1244 const MethodReference& method_ref = method_data.method_reference;
1245 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1246 size_t class_def_index = method_data.class_def_index;
1247 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001248 bool has_debug_info = method_data.HasDebugInfo();
1249 size_t debug_info_idx = method_data.debug_info_idx;
1250
1251 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1252
1253 // Derived from CompiledMethod.
1254 uint32_t quick_code_offset = 0;
1255
1256 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1257 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1258 uint32_t thumb_offset = compiled_method->CodeDelta();
1259
1260 // Deduplicate code arrays if we are not producing debuggable code.
1261 bool deduped = true;
1262 if (debuggable_) {
1263 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1264 if (quick_code_offset != 0u) {
1265 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1266 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001267 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001268 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1269 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001270 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001271 } else {
1272 quick_code_offset = dedupe_map_.GetOrCreate(
1273 compiled_method,
1274 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1275 deduped = false;
1276 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1277 });
1278 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001279
Igor Murashkin545412b2017-08-17 15:26:54 -07001280 if (code_size != 0) {
1281 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1282 // TODO: Should this be a hard failure?
1283 LOG(WARNING) << "Multiple definitions of "
1284 << method_ref.dex_file->PrettyMethod(method_ref.index)
1285 << " offsets " << relative_patcher_->GetOffset(method_ref)
1286 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001287 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001288 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1289 }
1290 }
1291
1292 // Update quick method header.
1293 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1294 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1295 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1296 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1297 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1298 // to 0-offset and we need to adjust it by code_offset.
1299 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001300 CHECK(!compiled_method->GetQuickCode().empty());
1301 // If the code is compiled, we write the offset of the stack map relative
1302 // to the code.
1303 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001304 vmap_table_offset += code_offset;
1305 DCHECK_LT(vmap_table_offset, code_offset);
1306 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001307 if (method_info_offset != 0u) {
1308 method_info_offset += code_offset;
1309 DCHECK_LT(method_info_offset, code_offset);
1310 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001311 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1312 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1313 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1314 *method_header = OatQuickMethodHeader(vmap_table_offset,
1315 method_info_offset,
1316 frame_size_in_bytes,
1317 core_spill_mask,
1318 fp_spill_mask,
1319 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001320
Igor Murashkin545412b2017-08-17 15:26:54 -07001321 if (!deduped) {
1322 // Update offsets. (Checksum is updated when writing.)
1323 offset_ += sizeof(*method_header); // Method header is prepended before code.
1324 offset_ += code_size;
1325 // Record absolute patch locations.
1326 if (!compiled_method->GetPatches().empty()) {
1327 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1328 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1329 if (!patch.IsPcRelative()) {
1330 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001331 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001332 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001333 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001334 }
1335
Igor Murashkin545412b2017-08-17 15:26:54 -07001336 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1337 if (generate_debug_info_ && code_size != 0) {
1338 DCHECK(has_debug_info);
1339
1340 bool has_code_info = method_header->IsOptimized();
1341 // Record debug information for this function if we are doing that.
1342 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
David Srbeckyc684f332018-01-19 17:38:06 +00001343 DCHECK(info.custom_name.empty());
Igor Murashkin545412b2017-08-17 15:26:54 -07001344 info.dex_file = method_ref.dex_file;
1345 info.class_def_index = class_def_index;
1346 info.dex_method_index = method_ref.index;
1347 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001348 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1349 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001350 info.isa = compiled_method->GetInstructionSet();
1351 info.deduped = deduped;
1352 info.is_native_debuggable = native_debuggable_;
1353 info.is_optimized = method_header->IsOptimized();
1354 info.is_code_address_text_relative = true;
1355 info.code_address = code_offset - executable_offset_;
1356 info.code_size = code_size;
1357 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1358 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1359 info.cfi = compiled_method->GetCFIInfo();
1360 } else {
1361 DCHECK(!has_debug_info);
1362 }
1363
1364 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1365 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1366 offsets->code_offset_ = quick_code_offset;
1367
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001368 return true;
1369 }
1370
Igor Murashkin545412b2017-08-17 15:26:54 -07001371 size_t GetOffset() const {
1372 return offset_;
1373 }
1374
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001375 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001376 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1377 size_t offset,
1378 const CompilerOptions& compiler_options,
1379 OrderedMethodList ordered_methods)
1380 : OrderedMethodVisitor(std::move(ordered_methods)),
1381 writer_(writer),
1382 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001383 relative_patcher_(writer->relative_patcher_),
1384 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1385 debuggable_(compiler_options.GetDebuggable()),
1386 native_debuggable_(compiler_options.GetNativeDebuggable()),
1387 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1388 writer->absolute_patch_locations_.reserve(
1389 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1390 }
1391
Vladimir Marko20f85592015-03-19 10:07:02 +00001392 struct CodeOffsetsKeyComparator {
1393 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001394 // Code is deduplicated by CompilerDriver, compare only data pointers.
1395 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1396 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001397 }
1398 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001399 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1400 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001401 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001402 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1403 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1404 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001405 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1406 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001407 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001408 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1409 return rhs->IsIntrinsic();
1410 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001411 return false;
1412 }
1413 };
1414
David Srbecky009e2a62015-04-15 02:46:30 +01001415 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001416 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001417 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001418 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001419 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1420 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001421 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1422 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1423 }
1424
Igor Murashkin545412b2017-08-17 15:26:54 -07001425 OatWriter* writer_;
1426
1427 // Offset of the code of the compiled methods.
1428 size_t offset_;
1429
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001430 // Deduplication is already done on a pointer basis by the compiler driver,
1431 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001432 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001433
Vladimir Marko1b404a82017-09-01 13:35:26 +01001434 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001435 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001436 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001437 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001438 const bool native_debuggable_;
1439 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001440};
1441
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001442class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1443 public:
1444 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001445 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001446
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001447 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001448 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001449 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001450 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1451
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001452 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001453 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001454 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001455
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001456 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1457 uint32_t map_size = map.size() * sizeof(map[0]);
1458 if (map_size != 0u) {
1459 size_t offset = dedupe_map_.GetOrCreate(
1460 map.data(),
1461 [this, map_size]() {
1462 uint32_t new_offset = offset_;
1463 offset_ += map_size;
1464 return new_offset;
1465 });
1466 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1467 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1468 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001469 }
1470 ++method_offsets_index_;
1471 }
1472
1473 return true;
1474 }
1475
1476 private:
1477 // Deduplication is already done on a pointer basis by the compiler driver,
1478 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001479 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001480};
1481
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001482class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1483 public:
1484 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1485
1486 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001487 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001488 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1489 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1490
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001491 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001492 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1493 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1494 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1495 const uint32_t map_size = map.size() * sizeof(map[0]);
1496 if (map_size != 0u) {
1497 size_t offset = dedupe_map_.GetOrCreate(
1498 map.data(),
1499 [this, map_size]() {
1500 uint32_t new_offset = offset_;
1501 offset_ += map_size;
1502 return new_offset;
1503 });
1504 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1505 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1506 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1507 }
1508 ++method_offsets_index_;
1509 }
1510
1511 return true;
1512 }
1513
1514 private:
1515 // Deduplication is already done on a pointer basis by the compiler driver,
1516 // so we can simply compare the pointers to find out if things are duplicated.
1517 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1518};
1519
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001520class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1521 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001522 InitImageMethodVisitor(OatWriter* writer,
1523 size_t offset,
1524 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001525 : OatDexMethodVisitor(writer, offset),
1526 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001527 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001528 dex_files_(dex_files),
1529 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001530
1531 // Handle copied methods here. Copy pointer to quick code from
1532 // an origin method to a copied method only if they are
1533 // in the same oat file. If the origin and the copied methods are
1534 // in different oat files don't touch the copied method.
1535 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001536 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001537 REQUIRES_SHARED(Locks::mutator_lock_) {
1538 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1539 // Skip classes that are not in the image.
1540 if (!IsImageClass()) {
1541 return true;
1542 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001543 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001544 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1545 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1546 if (klass != nullptr) {
1547 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1548 // Find origin method. Declaring class and dex_method_idx
1549 // in the copied method should be the same as in the origin
1550 // method.
1551 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001552 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001553 declaring_class->GetDexCache(),
1554 method.GetDexMethodIndex(),
1555 pointer_size_);
1556 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001557 CHECK(!origin->IsDirect());
1558 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001559 if (IsInOatFile(&declaring_class->GetDexFile())) {
1560 const void* code_ptr =
1561 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1562 if (code_ptr == nullptr) {
1563 methods_to_process_.push_back(std::make_pair(&method, origin));
1564 } else {
1565 method.SetEntryPointFromQuickCompiledCodePtrSize(
1566 code_ptr, pointer_size_);
1567 }
1568 }
1569 }
1570 }
1571 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001572 }
1573
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001574 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001575 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001576 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001577 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001578 return true;
1579 }
1580
Vladimir Marko49b0f452015-12-10 13:49:19 +00001581 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001582 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1583
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001584 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001585 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001586 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1587 offsets = oat_class->method_offsets_[method_offsets_index_];
1588 ++method_offsets_index_;
1589 }
1590
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001591 Thread* self = Thread::Current();
1592 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001593 ArtMethod* method;
1594 if (writer_->HasBootImage()) {
1595 const InvokeType invoke_type = it.GetMethodInvokeType(
1596 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001597 // Unchecked as we hold mutator_lock_ on entry.
1598 ScopedObjectAccessUnchecked soa(self);
1599 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001600 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001601 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001602 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001603 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Marko89011192017-12-11 13:45:05 +00001604 /* referrer */ nullptr,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001605 invoke_type);
1606 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001607 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001608 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001609 self->AssertPendingException();
1610 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001611 std::string dump = exc->Dump();
1612 LOG(FATAL) << dump;
1613 UNREACHABLE();
1614 }
1615 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001616 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001617 // 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 +01001618 // entrypoint. This is not fatal since we shall use a resolution method.
1619 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001620 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001621 if (method != nullptr &&
1622 compiled_method != nullptr &&
1623 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001624 method->SetEntryPointFromQuickCompiledCodePtrSize(
1625 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1626 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001627
1628 return true;
1629 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001630
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001631 // Check whether current class is image class
1632 bool IsImageClass() {
1633 const DexFile::TypeId& type_id =
1634 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1635 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1636 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1637 }
1638
1639 // Check whether specified dex file is in the compiled oat file.
1640 bool IsInOatFile(const DexFile* dex_file) {
1641 return ContainsElement(*dex_files_, dex_file);
1642 }
1643
1644 // Assign a pointer to quick code for copied methods
1645 // not handled in the method StartClass
1646 void Postprocess() {
1647 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1648 ArtMethod* method = p.first;
1649 ArtMethod* origin = p.second;
1650 const void* code_ptr =
1651 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1652 if (code_ptr != nullptr) {
1653 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1654 }
1655 }
1656 }
1657
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001658 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001659 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001660 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001661 const std::vector<const DexFile*>* dex_files_;
1662 ClassLinker* const class_linker_;
1663 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001664};
1665
Igor Murashkin545412b2017-08-17 15:26:54 -07001666class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001667 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001668 WriteCodeMethodVisitor(OatWriter* writer,
1669 OutputStream* out,
1670 const size_t file_offset,
1671 size_t relative_offset,
1672 OrderedMethodList ordered_methods)
1673 : OrderedMethodVisitor(std::move(ordered_methods)),
1674 writer_(writer),
1675 offset_(relative_offset),
1676 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001677 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1678 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1679 out_(out),
1680 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001681 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001682 dex_cache_(nullptr),
1683 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001684 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001685 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001686 // If we're creating the image, the address space must be ready so that we can apply patches.
1687 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001688 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001689 }
1690
Igor Murashkin545412b2017-08-17 15:26:54 -07001691 virtual bool VisitStart() OVERRIDE {
1692 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001693 }
1694
Igor Murashkin545412b2017-08-17 15:26:54 -07001695 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001696 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001697 dex_file_ = dex_file;
1698
1699 // Ordered method visiting is only for compiled methods.
1700 DCHECK(writer_->MayHaveCompiledMethods());
1701
Mathieu Chartier72041a02017-07-14 18:23:25 -07001702 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1703 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1704 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1705 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1706 DCHECK(dex_cache_ != nullptr);
1707 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001708 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001709 }
1710
1711 virtual bool VisitComplete() {
1712 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1713 if (UNLIKELY(offset_ == 0u)) {
1714 PLOG(ERROR) << "Failed to write final relative call thunks";
1715 return false;
1716 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001717 return true;
1718 }
1719
Igor Murashkin545412b2017-08-17 15:26:54 -07001720 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001721 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001722 const MethodReference& method_ref = method_data.method_reference;
1723 UpdateDexFileAndDexCache(method_ref.dex_file);
1724
1725 OatClass* oat_class = method_data.oat_class;
1726 CompiledMethod* compiled_method = method_data.compiled_method;
1727 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001728
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001729 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001730 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001731 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001732
Igor Murashkin545412b2017-08-17 15:26:54 -07001733 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1734 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1735 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001736
Igor Murashkin545412b2017-08-17 15:26:54 -07001737 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1738 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1739
1740 // Deduplicate code arrays.
1741 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1742 if (method_offsets.code_offset_ > offset_) {
1743 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1744 if (offset_ == 0u) {
1745 ReportWriteFailure("relative call thunk", method_ref);
1746 return false;
1747 }
1748 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1749 if (alignment_size != 0) {
1750 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1751 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001752 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001753 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001754 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001755 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001756 }
1757 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1758 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1759 DCHECK_EQ(method_offsets.code_offset_,
1760 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1761 << dex_file_->PrettyMethod(method_ref.index);
1762 const OatQuickMethodHeader& method_header =
1763 oat_class->method_headers_[method_offsets_index];
1764 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1765 ReportWriteFailure("method header", method_ref);
1766 return false;
1767 }
1768 writer_->size_method_header_ += sizeof(method_header);
1769 offset_ += sizeof(method_header);
1770 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001771
Igor Murashkin545412b2017-08-17 15:26:54 -07001772 if (!compiled_method->GetPatches().empty()) {
1773 patched_code_.assign(quick_code.begin(), quick_code.end());
1774 quick_code = ArrayRef<const uint8_t>(patched_code_);
1775 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1776 uint32_t literal_offset = patch.LiteralOffset();
1777 switch (patch.GetType()) {
1778 case LinkerPatch::Type::kMethodBssEntry: {
1779 uint32_t target_offset =
1780 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1781 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1782 patch,
1783 offset_ + literal_offset,
1784 target_offset);
1785 break;
1786 }
1787 case LinkerPatch::Type::kCallRelative: {
1788 // NOTE: Relative calls across oat files are not supported.
1789 uint32_t target_offset = GetTargetOffset(patch);
1790 writer_->relative_patcher_->PatchCall(&patched_code_,
1791 literal_offset,
1792 offset_ + literal_offset,
1793 target_offset);
1794 break;
1795 }
1796 case LinkerPatch::Type::kStringRelative: {
1797 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1798 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1799 patch,
1800 offset_ + literal_offset,
1801 target_offset);
1802 break;
1803 }
1804 case LinkerPatch::Type::kStringInternTable: {
1805 uint32_t target_offset = GetInternTableEntryOffset(patch);
1806 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1807 patch,
1808 offset_ + literal_offset,
1809 target_offset);
1810 break;
1811 }
1812 case LinkerPatch::Type::kStringBssEntry: {
1813 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1814 uint32_t target_offset =
1815 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1816 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1817 patch,
1818 offset_ + literal_offset,
1819 target_offset);
1820 break;
1821 }
1822 case LinkerPatch::Type::kTypeRelative: {
1823 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1824 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1825 patch,
1826 offset_ + literal_offset,
1827 target_offset);
1828 break;
1829 }
1830 case LinkerPatch::Type::kTypeClassTable: {
1831 uint32_t target_offset = GetClassTableEntryOffset(patch);
1832 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1833 patch,
1834 offset_ + literal_offset,
1835 target_offset);
1836 break;
1837 }
1838 case LinkerPatch::Type::kTypeBssEntry: {
1839 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1840 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1841 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1842 patch,
1843 offset_ + literal_offset,
1844 target_offset);
1845 break;
1846 }
1847 case LinkerPatch::Type::kCall: {
1848 uint32_t target_offset = GetTargetOffset(patch);
1849 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1850 break;
1851 }
1852 case LinkerPatch::Type::kMethodRelative: {
1853 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1854 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1855 patch,
1856 offset_ + literal_offset,
1857 target_offset);
1858 break;
1859 }
1860 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1861 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1862 patch,
1863 offset_ + literal_offset);
1864 break;
1865 }
1866 default: {
1867 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1868 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001869 }
1870 }
1871 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001872 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001873
1874 if (!out->WriteFully(quick_code.data(), code_size)) {
1875 ReportWriteFailure("method code", method_ref);
1876 return false;
1877 }
1878 writer_->size_code_ += code_size;
1879 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001880 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001881 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001882
1883 return true;
1884 }
1885
Igor Murashkin545412b2017-08-17 15:26:54 -07001886 size_t GetOffset() const {
1887 return offset_;
1888 }
1889
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001890 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001891 OatWriter* const writer_;
1892
1893 // Updated in VisitMethod as methods are written out.
1894 size_t offset_;
1895
1896 // Potentially varies with every different VisitMethod.
1897 // Used to determine which DexCache to use when finding ArtMethods.
1898 const DexFile* dex_file_;
1899
1900 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001901 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001902 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001903 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001904 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001905 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001906 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001907 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001908 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001909 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001910 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001911
Igor Murashkin545412b2017-08-17 15:26:54 -07001912 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001913 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001914 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001915 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001916
Mathieu Chartiere401d142015-04-22 13:56:20 -07001917 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001918 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001919 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001920 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001921 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1922 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001923 ArtMethod* method =
1924 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001925 CHECK(method != nullptr);
1926 return method;
1927 }
1928
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001929 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001930 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1931 // If there's no new compiled code, either we're compiling an app and the target method
1932 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001933 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001934 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001935 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001936 const void* oat_code_offset =
1937 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001938 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001939 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001940 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1941 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1942 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1943 target_offset = PointerToLowMemUInt32(oat_code_offset);
1944 } else {
1945 target_offset = target->IsNative()
1946 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1947 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1948 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001949 }
1950 return target_offset;
1951 }
1952
Vladimir Markocd556b02017-02-03 11:47:34 +00001953 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001954 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001955 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001956 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001957 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1958 }
1959
Vladimir Marko28e012a2017-12-07 11:22:59 +00001960 ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1961 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001962 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001963 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001964 ObjPtr<mirror::Class> type =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001965 class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001966 CHECK(type != nullptr);
Vladimir Marko28e012a2017-12-07 11:22:59 +00001967 return type;
Vladimir Markof4da6752014-08-01 19:04:18 +01001968 }
1969
Vladimir Marko28e012a2017-12-07 11:22:59 +00001970 ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1971 REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001972 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Markoa64b52d2017-12-08 16:27:49 +00001973 ObjPtr<mirror::String> string =
1974 linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001975 DCHECK(string != nullptr);
1976 DCHECK(writer_->HasBootImage() ||
1977 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1978 return string;
1979 }
1980
Vladimir Marko65979462017-05-19 17:25:12 +01001981 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1982 DCHECK(writer_->HasBootImage());
1983 method = writer_->image_writer_->GetImageMethodAddress(method);
1984 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1985 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1986 // TODO: Clean up offset types. The target offset must be treated as signed.
1987 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1988 }
1989
Vladimir Marko28e012a2017-12-07 11:22:59 +00001990 uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
1991 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001992 DCHECK(writer_->HasBootImage());
Vladimir Marko28e012a2017-12-07 11:22:59 +00001993 object = writer_->image_writer_->GetImageAddress(object.Ptr());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001994 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1995 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1996 // TODO: Clean up offset types. The target offset must be treated as signed.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001997 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001998 }
1999
Vladimir Markof4da6752014-08-01 19:04:18 +01002000 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002001 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002002 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002003 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01002004 } else {
2005 // NOTE: We're using linker patches for app->boot references when the image can
2006 // be relocated and therefore we need to emit .oat_patches. We're not using this
2007 // for app->app references, so check that the object is in the image space.
2008 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01002009 }
Vladimir Marko09d09432015-09-08 13:47:48 +01002010 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01002011 uint32_t address = PointerToLowMemUInt32(object);
2012 DCHECK_LE(offset + 4, code->size());
2013 uint8_t* data = &(*code)[offset];
2014 data[0] = address & 0xffu;
2015 data[1] = (address >> 8) & 0xffu;
2016 data[2] = (address >> 16) & 0xffu;
2017 data[3] = (address >> 24) & 0xffu;
2018 }
2019
2020 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002021 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01002022 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002023 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002024 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
2025 // TODO: Clean up offset types.
2026 // The target_offset must be treated as signed for cross-oat patching.
2027 const void* target = reinterpret_cast<const void*>(
2028 writer_->image_writer_->GetOatDataBegin(oat_index) +
2029 static_cast<int32_t>(target_offset));
2030 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01002031 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002032 DCHECK_LE(offset + 4, code->size());
2033 uint8_t* data = &(*code)[offset];
2034 data[0] = address & 0xffu;
2035 data[1] = (address >> 8) & 0xffu;
2036 data[2] = (address >> 16) & 0xffu;
2037 data[3] = (address >> 24) & 0xffu;
2038 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002039
2040 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
2041 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
2042 REQUIRES_SHARED(Locks::mutator_lock_) {
2043 DCHECK(!writer_->HasBootImage());
2044 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
2045 *patch.TargetStringDexFile(), patch.TargetStringIndex());
2046 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002047 return GetBootImageTableEntryOffset(string_root);
2048 }
2049
2050 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
2051 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
2052 REQUIRES_SHARED(Locks::mutator_lock_) {
2053 DCHECK(!writer_->HasBootImage());
2054 const uint8_t* table_slot =
2055 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
2056 DCHECK(table_slot != nullptr);
2057 return GetBootImageTableEntryOffset(table_slot);
2058 }
2059
2060 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002061 uint32_t base_offset = writer_->bss_start_;
2062 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2063 const uint8_t* const_tables_begin =
2064 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002065 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002066 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
2067 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
2068 return base_offset + offset;
2069 }
2070 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
2071 }
2072 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
2073 UNREACHABLE();
2074 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002075};
2076
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002077class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2078 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002079 WriteMapMethodVisitor(OatWriter* writer,
2080 OutputStream* out,
2081 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002082 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002083 : OatDexMethodVisitor(writer, relative_offset),
2084 out_(out),
2085 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002086
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002087 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002088 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002089 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2090
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002091 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002092 size_t file_offset = file_offset_;
2093 OutputStream* out = out_;
2094
Mingyao Yang063fc772016-08-02 11:02:54 -07002095 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002096 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002097 ++method_offsets_index_;
2098
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002099 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2100 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2101 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002102 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002103
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002104 // If vdex is enabled, only emit the map for compiled code. The quickening info
2105 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002106 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002107 // Transform map_offset to actual oat data offset.
2108 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2109 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002110 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002111
2112 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2113 size_t map_size = map.size() * sizeof(map[0]);
2114 if (map_offset == offset_) {
2115 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002116 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002117 ReportWriteFailure(it);
2118 return false;
2119 }
2120 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002121 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002122 }
2123 DCHECK_OFFSET_();
2124 }
2125
2126 return true;
2127 }
2128
2129 private:
2130 OutputStream* const out_;
2131 size_t const file_offset_;
2132
2133 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002134 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002135 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002136 }
2137};
2138
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002139class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2140 public:
2141 WriteMethodInfoVisitor(OatWriter* writer,
2142 OutputStream* out,
2143 const size_t file_offset,
2144 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002145 : OatDexMethodVisitor(writer, relative_offset),
2146 out_(out),
2147 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002148
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002149 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002150 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2151 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2152
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002153 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002154 size_t file_offset = file_offset_;
2155 OutputStream* out = out_;
2156 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2157 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2158 ++method_offsets_index_;
2159 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2160 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2161 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2162 << dex_file_->PrettyMethod(it.GetMemberIndex());
2163 if (map_offset != 0u) {
2164 // Transform map_offset to actual oat data offset.
2165 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2166 DCHECK_NE(map_offset, 0u);
2167 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2168
2169 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2170 size_t map_size = map.size() * sizeof(map[0]);
2171 if (map_offset == offset_) {
2172 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2173 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2174 ReportWriteFailure(it);
2175 return false;
2176 }
2177 offset_ += map_size;
2178 }
2179 }
2180 DCHECK_OFFSET_();
2181 }
2182
2183 return true;
2184 }
2185
2186 private:
2187 OutputStream* const out_;
2188 size_t const file_offset_;
2189
2190 void ReportWriteFailure(const ClassDataItemIterator& it) {
2191 PLOG(ERROR) << "Failed to write map for "
2192 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2193 }
2194};
2195
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002196// Visit all methods from all classes in all dex files with the specified visitor.
2197bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2198 for (const DexFile* dex_file : *dex_files_) {
2199 const size_t class_def_count = dex_file->NumClassDefs();
2200 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2201 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2202 return false;
2203 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002204 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002205 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2206 const uint8_t* class_data = dex_file->GetClassData(class_def);
2207 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2208 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002209 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002210 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002211 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002212 if (!visitor->VisitMethod(class_def_method_index, it)) {
2213 return false;
2214 }
2215 ++class_def_method_index;
2216 it.Next();
2217 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002218 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002219 }
2220 }
2221 if (UNLIKELY(!visitor->EndClass())) {
2222 return false;
2223 }
2224 }
2225 }
2226 return true;
2227}
2228
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002229size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2230 const InstructionSetFeatures* instruction_set_features,
2231 uint32_t num_dex_files,
2232 SafeMap<std::string, std::string>* key_value_store) {
2233 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2234 oat_header_.reset(OatHeader::Create(instruction_set,
2235 instruction_set_features,
2236 num_dex_files,
2237 key_value_store));
2238 size_oat_header_ += sizeof(OatHeader);
2239 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002240 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002241}
2242
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002243size_t OatWriter::InitClassOffsets(size_t offset) {
2244 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002245 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002246 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2247 if (!oat_dex_file.class_offsets_.empty()) {
2248 // Class offsets are required to be 4 byte aligned.
2249 offset = RoundUp(offset, 4u);
2250 oat_dex_file.class_offsets_offset_ = offset;
2251 offset += oat_dex_file.GetClassOffsetsRawSize();
2252 DCHECK_ALIGNED(offset, 4u);
2253 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002254 }
2255 return offset;
2256}
2257
Brian Carlstrom389efb02012-01-11 12:06:26 -08002258size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002259 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002260 InitOatClassesMethodVisitor visitor(this, offset);
2261 bool success = VisitDexMethods(&visitor);
2262 CHECK(success);
2263 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002264
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002265 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002266 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002267 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2268 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002269 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002270 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002271 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002272 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002273 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002274 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002275
2276 return offset;
2277}
2278
2279size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002280 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002281 return offset;
2282 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002283 {
2284 InitMapMethodVisitor visitor(this, offset);
2285 bool success = VisitDexMethods(&visitor);
2286 DCHECK(success);
2287 offset = visitor.GetOffset();
2288 }
2289 {
2290 InitMethodInfoVisitor visitor(this, offset);
2291 bool success = VisitDexMethods(&visitor);
2292 DCHECK(success);
2293 offset = visitor.GetOffset();
2294 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002295 return offset;
2296}
2297
Vladimir Markof3c52b42017-11-17 17:32:12 +00002298template <typename GetBssOffset>
2299static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2300 size_t slot_size,
2301 const BitVector& indexes,
2302 GetBssOffset get_bss_offset) {
2303 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2304 size_t number_of_entries = 0u;
2305 bool first_index = true;
2306 for (uint32_t index : indexes.Indexes()) {
2307 uint32_t bss_offset = get_bss_offset(index);
2308 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2309 encoder.Reset(index, bss_offset);
2310 ++number_of_entries;
2311 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002312 }
2313 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002314 DCHECK_NE(number_of_entries, 0u);
2315 return number_of_entries;
2316}
2317
2318template <typename GetBssOffset>
2319static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2320 size_t slot_size,
2321 const BitVector& indexes,
2322 GetBssOffset get_bss_offset) {
2323 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2324 slot_size,
2325 indexes,
2326 get_bss_offset);
2327 return IndexBssMapping::ComputeSize(number_of_entries);
2328}
2329
2330size_t OatWriter::InitIndexBssMappings(size_t offset) {
2331 if (bss_method_entry_references_.empty() &&
2332 bss_type_entry_references_.empty() &&
2333 bss_string_entry_references_.empty()) {
2334 return offset;
2335 }
2336 // If there are any classes, the class offsets allocation aligns the offset
2337 // and we cannot have any index bss mappings without class offsets.
2338 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2339 DCHECK_ALIGNED(offset, 4u);
2340
2341 size_t number_of_method_dex_files = 0u;
2342 size_t number_of_type_dex_files = 0u;
2343 size_t number_of_string_dex_files = 0u;
2344 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2345 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2346 const DexFile* dex_file = (*dex_files_)[i];
2347 auto method_it = bss_method_entry_references_.find(dex_file);
2348 if (method_it != bss_method_entry_references_.end()) {
2349 const BitVector& method_indexes = method_it->second;
2350 ++number_of_method_dex_files;
2351 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2352 offset += CalculateIndexBssMappingSize(
2353 dex_file->NumMethodIds(),
2354 static_cast<size_t>(pointer_size),
2355 method_indexes,
2356 [=](uint32_t index) {
2357 return bss_method_entries_.Get({dex_file, index});
2358 });
2359 }
2360
2361 auto type_it = bss_type_entry_references_.find(dex_file);
2362 if (type_it != bss_type_entry_references_.end()) {
2363 const BitVector& type_indexes = type_it->second;
2364 ++number_of_type_dex_files;
2365 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2366 offset += CalculateIndexBssMappingSize(
2367 dex_file->NumTypeIds(),
2368 sizeof(GcRoot<mirror::Class>),
2369 type_indexes,
2370 [=](uint32_t index) {
2371 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2372 });
2373 }
2374
2375 auto string_it = bss_string_entry_references_.find(dex_file);
2376 if (string_it != bss_string_entry_references_.end()) {
2377 const BitVector& string_indexes = string_it->second;
2378 ++number_of_string_dex_files;
2379 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2380 offset += CalculateIndexBssMappingSize(
2381 dex_file->NumStringIds(),
2382 sizeof(GcRoot<mirror::String>),
2383 string_indexes,
2384 [=](uint32_t index) {
2385 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2386 });
2387 }
2388 }
2389 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2390 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2391 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2392 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002393 return offset;
2394}
2395
2396size_t OatWriter::InitOatDexFiles(size_t offset) {
2397 // Initialize offsets of oat dex files.
2398 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2399 oat_dex_file.offset_ = offset;
2400 offset += oat_dex_file.SizeOf();
2401 }
2402 return offset;
2403}
2404
Brian Carlstrome24fa612011-09-29 00:53:55 -07002405size_t OatWriter::InitOatCode(size_t offset) {
2406 // calculate the offsets within OatHeader to executable code
2407 size_t old_offset = offset;
2408 // required to be on a new page boundary
2409 offset = RoundUp(offset, kPageSize);
2410 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002411 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002412 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2413 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2414 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002415 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002416 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002417 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2418 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002419
Vladimir Marko1b404a82017-09-01 13:35:26 +01002420 #define DO_TRAMPOLINE(field, fn_name) \
2421 offset = CompiledCode::AlignCode(offset, instruction_set); \
2422 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2423 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2424 (field) = compiler_driver_->Create ## fn_name(); \
2425 if (generate_debug_info) { \
2426 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +00002427 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +01002428 info.isa = instruction_set; \
2429 info.is_code_address_text_relative = true; \
2430 /* Use the code offset rather than the `adjusted_offset`. */ \
2431 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2432 info.code_size = (field)->size(); \
2433 method_info_.push_back(std::move(info)); \
2434 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002435 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002436
Ian Rogers848871b2013-08-05 10:56:33 -07002437 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002438 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002439 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002440 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2441 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002442
Ian Rogers848871b2013-08-05 10:56:33 -07002443 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002444 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002445 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002446 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002447 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002448 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002449 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002450 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002451 return offset;
2452}
2453
2454size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002455 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002456 if (kOatWriterDebugOatCodeLayout) {
2457 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2458 << this << "), "
2459 << "compilation is disabled";
2460 }
2461
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002462 return offset;
2463 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002464 bool success = false;
2465
2466 {
2467 ScopedObjectAccess soa(Thread::Current());
2468
2469 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2470 success = VisitDexMethods(&layout_code_visitor);
2471 DCHECK(success);
2472
2473 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2474 this,
2475 offset,
2476 layout_code_visitor.ReleaseOrderedMethods());
2477 success = layout_reserve_code_visitor.Visit();
2478 DCHECK(success);
2479 offset = layout_reserve_code_visitor.GetOffset();
2480
2481 // Save the method order because the WriteCodeMethodVisitor will need this
2482 // order again.
2483 DCHECK(ordered_methods_ == nullptr);
2484 ordered_methods_.reset(
2485 new OrderedMethodList(
2486 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2487
2488 if (kOatWriterDebugOatCodeLayout) {
2489 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2490 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2491 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2492 LOG(INFO) << pretty_name
2493 << "@ offset "
2494 << relative_patcher_->GetOffset(ordered_method.method_reference)
2495 << " X hotness "
2496 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2497 }
2498 }
2499 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002500
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002501 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002502 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002503 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002504 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002505 DCHECK(success);
2506 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002507 }
Logan Chien8b977d32012-02-21 19:14:55 +08002508
Brian Carlstrome24fa612011-09-29 00:53:55 -07002509 return offset;
2510}
2511
Vladimir Markoaad75c62016-10-03 08:46:48 +00002512void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002513 {
2514 InitBssLayoutMethodVisitor visitor(this);
2515 bool success = VisitDexMethods(&visitor);
2516 DCHECK(success);
2517 }
2518
2519 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002520 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002521 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002522 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002523 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002524 if (!map_boot_image_tables_to_bss_ &&
2525 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002526 bss_type_entries_.empty() &&
2527 bss_string_entries_.empty()) {
2528 // Nothing to put to the .bss section.
2529 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002530 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002531
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002532 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002533 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002534 if (map_boot_image_tables_to_bss_) {
2535 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2536 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2537 }
2538 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002539
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002540 bss_methods_offset_ = bss_size_;
2541
2542 // Prepare offsets for .bss ArtMethod entries.
2543 for (auto& entry : bss_method_entries_) {
2544 DCHECK_EQ(entry.second, 0u);
2545 entry.second = bss_size_;
2546 bss_size_ += static_cast<size_t>(pointer_size);
2547 }
2548
Vladimir Markoaad75c62016-10-03 08:46:48 +00002549 bss_roots_offset_ = bss_size_;
2550
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002551 // Prepare offsets for .bss Class entries.
2552 for (auto& entry : bss_type_entries_) {
2553 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002554 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002555 bss_size_ += sizeof(GcRoot<mirror::Class>);
2556 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002557 // Prepare offsets for .bss String entries.
2558 for (auto& entry : bss_string_entries_) {
2559 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002560 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002561 bss_size_ += sizeof(GcRoot<mirror::String>);
2562 }
2563}
2564
David Srbeckybc90fd02015-04-22 19:40:27 +01002565bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002566 CHECK(write_state_ == WriteState::kWriteRoData);
2567
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002568 size_t file_offset = oat_data_offset_;
2569 off_t current_offset = out->Seek(0, kSeekCurrent);
2570 if (current_offset == static_cast<off_t>(-1)) {
2571 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2572 }
2573 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2574 size_t relative_offset = current_offset - file_offset;
2575
Vladimir Markoe079e212016-05-25 12:49:49 +01002576 // Wrap out to update checksum with each write.
2577 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2578 out = &checksum_updating_out;
2579
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002580 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2581 if (relative_offset == 0) {
2582 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002583 return false;
2584 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002585
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002586 relative_offset = WriteClasses(out, file_offset, relative_offset);
2587 if (relative_offset == 0) {
2588 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002589 return false;
2590 }
2591
Vladimir Markof3c52b42017-11-17 17:32:12 +00002592 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002593 if (relative_offset == 0) {
2594 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002595 return false;
2596 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002597
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002598 relative_offset = WriteMaps(out, file_offset, relative_offset);
2599 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002600 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2601 return false;
2602 }
2603
2604 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2605 if (relative_offset == 0) {
2606 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002607 return false;
2608 }
2609
David Srbeckybc90fd02015-04-22 19:40:27 +01002610 // Write padding.
2611 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2612 relative_offset += size_executable_offset_alignment_;
2613 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2614 size_t expected_file_offset = file_offset + relative_offset;
2615 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2616 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2617 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2618 return 0;
2619 }
2620 DCHECK_OFFSET();
2621
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002622 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002623 return true;
2624}
2625
Mathieu Chartier210531f2018-01-12 10:15:51 -08002626class OatWriter::WriteQuickeningInfoMethodVisitor {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002627 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002628 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out)
2629 : writer_(writer),
2630 out_(out) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002631
Mathieu Chartier210531f2018-01-12 10:15:51 -08002632 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
2633 std::vector<uint8_t> empty_quicken_info;
2634 {
2635 // Since we need to be able to access by dex method index, put a one byte empty quicken info
2636 // for any method that isn't quickened.
2637 QuickenInfoTable::Builder empty_info(&empty_quicken_info, /*num_elements*/ 0u);
2638 CHECK(!empty_quicken_info.empty());
2639 }
2640 for (const DexFile* dex_file : dex_files) {
2641 std::vector<uint32_t>* const offsets =
2642 &quicken_info_offset_indices_.Put(dex_file, std::vector<uint32_t>())->second;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002643
Mathieu Chartier210531f2018-01-12 10:15:51 -08002644 // Every method needs an index in the table.
2645 for (uint32_t method_idx = 0; method_idx < dex_file->NumMethodIds(); ++method_idx) {
2646 ArrayRef<const uint8_t> map(empty_quicken_info);
2647
2648 // Use the existing quicken info if it exists.
2649 MethodReference method_ref(dex_file, method_idx);
2650 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(method_ref);
2651 if (compiled_method != nullptr && HasQuickeningInfo(compiled_method)) {
2652 map = compiled_method->GetVmapTable();
2653 }
2654
2655 // The current approach prevents deduplication of quicken infos since each method index
2656 // has one unique quicken info. Deduplication does not provide much savings for dex indices
2657 // since they are rarely duplicated.
2658 const uint32_t length = map.size() * sizeof(map.front());
2659
2660 // Record each index if required. written_bytes_ is the offset from the start of the
2661 // quicken info data.
2662 if (QuickenInfoOffsetTableAccessor::IsCoveredIndex(method_idx)) {
2663 offsets->push_back(written_bytes_);
2664 }
2665
2666 if (!out_->WriteFully(map.data(), length)) {
2667 PLOG(ERROR) << "Failed to write quickening info for " << method_ref.PrettyMethod()
2668 << " to " << out_->GetLocation();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002669 return false;
2670 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002671 written_bytes_ += length;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002672 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002673 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002674 return true;
2675 }
2676
2677 size_t GetNumberOfWrittenBytes() const {
2678 return written_bytes_;
2679 }
2680
Mathieu Chartier210531f2018-01-12 10:15:51 -08002681 SafeMap<const DexFile*, std::vector<uint32_t>>& GetQuickenInfoOffsetIndicies() {
2682 return quicken_info_offset_indices_;
2683 }
2684
2685
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002686 private:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002687 OatWriter* const writer_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002688 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002689 size_t written_bytes_ = 0u;
2690 // Map of offsets for quicken info related to method indices.
2691 SafeMap<const DexFile*, std::vector<uint32_t>> quicken_info_offset_indices_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002692};
2693
Mathieu Chartier210531f2018-01-12 10:15:51 -08002694class OatWriter::WriteQuickeningInfoOffsetsMethodVisitor {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002695 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002696 WriteQuickeningInfoOffsetsMethodVisitor(
2697 OutputStream* out,
2698 uint32_t start_offset,
2699 SafeMap<const DexFile*, std::vector<uint32_t>>* quicken_info_offset_indices,
2700 std::vector<uint32_t>* out_table_offsets)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002701 : out_(out),
Mathieu Chartier210531f2018-01-12 10:15:51 -08002702 start_offset_(start_offset),
2703 quicken_info_offset_indices_(quicken_info_offset_indices),
2704 out_table_offsets_(out_table_offsets) {}
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002705
Mathieu Chartier210531f2018-01-12 10:15:51 -08002706 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002707 for (const DexFile* dex_file : dex_files) {
Mathieu Chartier210531f2018-01-12 10:15:51 -08002708 auto it = quicken_info_offset_indices_->find(dex_file);
2709 DCHECK(it != quicken_info_offset_indices_->end()) << "Failed to find dex file "
2710 << dex_file->GetLocation();
2711 const std::vector<uint32_t>* const offsets = &it->second;
2712
2713 const uint32_t current_offset = start_offset_ + written_bytes_;
2714 CHECK_ALIGNED_PARAM(current_offset, QuickenInfoOffsetTableAccessor::Alignment());
2715
2716 // Generate and write the data.
2717 std::vector<uint8_t> table_data;
2718 QuickenInfoOffsetTableAccessor::Builder builder(&table_data);
2719 for (uint32_t offset : *offsets) {
2720 builder.AddOffset(offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002721 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002722
2723 // Store the offset since we need to put those after the dex file. Table offsets are relative
2724 // to the start of the quicken info section.
2725 out_table_offsets_->push_back(current_offset);
2726
2727 const uint32_t length = table_data.size() * sizeof(table_data.front());
2728 if (!out_->WriteFully(table_data.data(), length)) {
2729 PLOG(ERROR) << "Failed to write quickening offset table for " << dex_file->GetLocation()
2730 << " to " << out_->GetLocation();
2731 return false;
2732 }
2733 written_bytes_ += length;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002734 }
2735 return true;
2736 }
2737
2738 size_t GetNumberOfWrittenBytes() const {
2739 return written_bytes_;
2740 }
2741
2742 private:
2743 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002744 const uint32_t start_offset_;
2745 size_t written_bytes_ = 0u;
2746 // Maps containing the offsets for the tables.
2747 SafeMap<const DexFile*, std::vector<uint32_t>>* const quicken_info_offset_indices_;
2748 std::vector<uint32_t>* const out_table_offsets_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002749};
2750
2751bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002752 if (only_contains_uncompressed_zip_entries_) {
2753 // Nothing to write. Leave `vdex_size_` untouched and unaligned.
2754 vdex_quickening_info_offset_ = vdex_size_;
2755 size_quickening_info_alignment_ = 0;
2756 return true;
2757 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002758 size_t initial_offset = vdex_size_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002759 // Make sure the table is properly aligned.
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002760 size_t start_offset = RoundUp(initial_offset, 4u);
2761
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002762 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2763 if (actual_offset != static_cast<off_t>(start_offset)) {
2764 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2765 << " Expected: " << start_offset
2766 << " Output: " << vdex_out->GetLocation();
2767 return false;
2768 }
2769
Mathieu Chartier210531f2018-01-12 10:15:51 -08002770 size_t current_offset = start_offset;
2771 if (compiler_driver_->GetCompilerOptions().IsQuickeningCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002772 std::vector<uint32_t> dex_files_indices;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002773 WriteQuickeningInfoMethodVisitor write_quicken_info_visitor(this, vdex_out);
2774 if (!write_quicken_info_visitor.VisitDexMethods(*dex_files_)) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002775 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2776 return false;
2777 }
2778
Mathieu Chartier210531f2018-01-12 10:15:51 -08002779 uint32_t quicken_info_offset = write_quicken_info_visitor.GetNumberOfWrittenBytes();
2780 current_offset = current_offset + quicken_info_offset;
2781 uint32_t before_offset = current_offset;
2782 current_offset = RoundUp(current_offset, QuickenInfoOffsetTableAccessor::Alignment());
2783 const size_t extra_bytes = current_offset - before_offset;
2784 quicken_info_offset += extra_bytes;
2785 actual_offset = vdex_out->Seek(current_offset, kSeekSet);
2786 if (actual_offset != static_cast<off_t>(current_offset)) {
2787 PLOG(ERROR) << "Failed to seek to quickening offset table section. Actual: " << actual_offset
2788 << " Expected: " << current_offset
2789 << " Output: " << vdex_out->GetLocation();
2790 return false;
2791 }
2792
2793 std::vector<uint32_t> table_offsets;
2794 WriteQuickeningInfoOffsetsMethodVisitor table_visitor(
2795 vdex_out,
2796 quicken_info_offset,
2797 &write_quicken_info_visitor.GetQuickenInfoOffsetIndicies(),
2798 /*out*/ &table_offsets);
2799 if (!table_visitor.VisitDexMethods(*dex_files_)) {
2800 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2801 << vdex_out->GetLocation();
2802 return false;
2803 }
2804
2805 CHECK_EQ(table_offsets.size(), dex_files_->size());
2806
2807 current_offset += table_visitor.GetNumberOfWrittenBytes();
2808
2809 // Store the offset table offset as a preheader for each dex.
2810 size_t index = 0;
2811 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
2812 const off_t desired_offset = oat_dex_file.dex_file_offset_ -
2813 sizeof(VdexFile::QuickeningTableOffsetType);
2814 actual_offset = vdex_out->Seek(desired_offset, kSeekSet);
2815 if (actual_offset != desired_offset) {
2816 PLOG(ERROR) << "Failed to seek to before dex file for writing offset table offset: "
2817 << actual_offset << " Expected: " << desired_offset
2818 << " Output: " << vdex_out->GetLocation();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002819 return false;
2820 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002821 uint32_t offset = table_offsets[index];
2822 if (!vdex_out->WriteFully(reinterpret_cast<const uint8_t*>(&offset), sizeof(offset))) {
2823 PLOG(ERROR) << "Failed to write verifier deps."
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002824 << " File: " << vdex_out->GetLocation();
2825 return false;
2826 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002827 ++index;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002828 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002829 if (!vdex_out->Flush()) {
2830 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2831 << " File: " << vdex_out->GetLocation();
2832 return false;
2833 }
2834 size_quickening_info_ = current_offset - start_offset;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002835 } else {
2836 // We know we did not quicken.
2837 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002838 }
2839
David Brazdil93592f52017-12-08 10:53:27 +00002840 if (size_quickening_info_ == 0) {
2841 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2842 vdex_quickening_info_offset_ = initial_offset;
2843 size_quickening_info_alignment_ = 0;
2844 } else {
2845 vdex_size_ = start_offset + size_quickening_info_;
2846 vdex_quickening_info_offset_ = start_offset;
2847 size_quickening_info_alignment_ = start_offset - initial_offset;
2848 }
2849
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002850 return true;
2851}
2852
David Brazdil5d5a36b2016-09-14 15:34:10 +01002853bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002854 if (verifier_deps == nullptr) {
2855 // Nothing to write. Record the offset, but no need
2856 // for alignment.
2857 vdex_verifier_deps_offset_ = vdex_size_;
2858 return true;
2859 }
2860
2861 size_t initial_offset = vdex_size_;
2862 size_t start_offset = RoundUp(initial_offset, 4u);
2863
2864 vdex_size_ = start_offset;
2865 vdex_verifier_deps_offset_ = vdex_size_;
2866 size_verifier_deps_alignment_ = start_offset - initial_offset;
2867
2868 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2869 if (actual_offset != static_cast<off_t>(start_offset)) {
2870 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2871 << " Expected: " << start_offset
2872 << " Output: " << vdex_out->GetLocation();
2873 return false;
2874 }
2875
2876 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002877 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002878
2879 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2880 PLOG(ERROR) << "Failed to write verifier deps."
2881 << " File: " << vdex_out->GetLocation();
2882 return false;
2883 }
2884 if (!vdex_out->Flush()) {
2885 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2886 << " File: " << vdex_out->GetLocation();
2887 return false;
2888 }
2889
2890 size_verifier_deps_ = buffer.size();
2891 vdex_size_ += size_verifier_deps_;
2892 return true;
2893}
2894
David Srbeckybc90fd02015-04-22 19:40:27 +01002895bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002896 CHECK(write_state_ == WriteState::kWriteText);
2897
Vladimir Markoe079e212016-05-25 12:49:49 +01002898 // Wrap out to update checksum with each write.
2899 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2900 out = &checksum_updating_out;
2901
Vladimir Marko944da602016-02-19 12:27:55 +00002902 SetMultiOatRelativePatcherAdjustment();
2903
David Srbeckybc90fd02015-04-22 19:40:27 +01002904 const size_t file_offset = oat_data_offset_;
2905 size_t relative_offset = oat_header_->GetExecutableOffset();
2906 DCHECK_OFFSET();
2907
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002908 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002909 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002910 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002911 return false;
2912 }
2913
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002914 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2915 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002916 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002917 return false;
2918 }
2919
Vladimir Markof4da6752014-08-01 19:04:18 +01002920 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002921 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002922 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2923 return false;
2924 }
2925
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002926 if (kIsDebugBuild) {
2927 uint32_t size_total = 0;
2928 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002929 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2930 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002931
David Brazdil7b49e6c2016-09-01 11:06:18 +01002932 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002933 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002934 DO_STAT(size_dex_file_alignment_);
2935 DO_STAT(size_executable_offset_alignment_);
2936 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002937 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002938 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002939 DO_STAT(size_verifier_deps_);
2940 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002941 DO_STAT(size_quickening_info_);
2942 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002943 DO_STAT(size_interpreter_to_interpreter_bridge_);
2944 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2945 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002946 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002947 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002948 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002949 DO_STAT(size_quick_to_interpreter_bridge_);
2950 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002951 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002952 DO_STAT(size_code_);
2953 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002954 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002955 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002956 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002957 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002958 DO_STAT(size_oat_dex_file_location_size_);
2959 DO_STAT(size_oat_dex_file_location_data_);
2960 DO_STAT(size_oat_dex_file_location_checksum_);
2961 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002962 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002963 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002964 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2965 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2966 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002967 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002968 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2969 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002970 DO_STAT(size_oat_lookup_table_alignment_);
2971 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002972 DO_STAT(size_oat_class_offsets_alignment_);
2973 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002974 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002975 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002976 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002977 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002978 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002979 DO_STAT(size_type_bss_mappings_);
2980 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002981 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002982
David Brazdil7b49e6c2016-09-01 11:06:18 +01002983 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2984
2985 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2986 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002987 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002988
David Brazdil7b49e6c2016-09-01 11:06:18 +01002989 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2990 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002991
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002992 write_state_ = WriteState::kWriteHeader;
2993 return true;
2994}
2995
2996bool OatWriter::WriteHeader(OutputStream* out,
2997 uint32_t image_file_location_oat_checksum,
2998 uintptr_t image_file_location_oat_begin,
2999 int32_t image_patch_delta) {
3000 CHECK(write_state_ == WriteState::kWriteHeader);
3001
3002 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
3003 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00003004 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003005 CHECK_EQ(image_patch_delta, 0);
3006 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
3007 } else {
3008 CHECK_ALIGNED(image_patch_delta, kPageSize);
3009 oat_header_->SetImagePatchDelta(image_patch_delta);
3010 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003011 oat_header_->UpdateChecksumWithHeaderData();
3012
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003013 const size_t file_offset = oat_data_offset_;
3014
3015 off_t current_offset = out->Seek(0, kSeekCurrent);
3016 if (current_offset == static_cast<off_t>(-1)) {
3017 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
3018 return false;
3019 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003020 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003021 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
3022 return false;
3023 }
David Srbeckybc90fd02015-04-22 19:40:27 +01003024 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003025
3026 // Flush all other data before writing the header.
3027 if (!out->Flush()) {
3028 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
3029 return false;
3030 }
3031 // Write the header.
3032 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00003033 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003034 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
3035 return false;
3036 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003037 // Flush the header data.
3038 if (!out->Flush()) {
3039 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01003040 return false;
3041 }
Vladimir Markof4da6752014-08-01 19:04:18 +01003042
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003043 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
3044 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
3045 return false;
3046 }
3047 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
3048
3049 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003050 return true;
3051}
3052
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003053size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003054 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3055 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003056 // Class offsets are required to be 4 byte aligned.
3057 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
3058 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
3059 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
3060 return 0u;
3061 }
3062 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00003063 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003064 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003065 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003066 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003067 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003068 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003069 }
3070 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003071 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003072}
3073
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003074size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003075 const bool may_have_compiled = MayHaveCompiledMethods();
3076 if (may_have_compiled) {
3077 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
3078 }
3079 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003080 // If there are any classes, the class offsets allocation aligns the offset.
3081 DCHECK_ALIGNED(relative_offset, 4u);
3082 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003083 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003084 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00003085 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003086 relative_offset += oat_class_headers_[i].SizeOf();
3087 if (may_have_compiled) {
3088 if (!oat_classes_[i].Write(this, out)) {
3089 return 0u;
3090 }
3091 relative_offset += oat_classes_[i].SizeOf();
3092 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003093 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003094 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003095}
3096
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003097size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003098 {
3099 size_t vmap_tables_offset = relative_offset;
3100 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
3101 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3102 return 0;
3103 }
3104 relative_offset = visitor.GetOffset();
3105 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003106 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003107 {
3108 size_t method_infos_offset = relative_offset;
3109 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
3110 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3111 return 0;
3112 }
3113 relative_offset = visitor.GetOffset();
3114 size_method_info_ = relative_offset - method_infos_offset;
3115 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003116
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003117 return relative_offset;
3118}
3119
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003120
Vladimir Markof3c52b42017-11-17 17:32:12 +00003121template <typename GetBssOffset>
3122size_t WriteIndexBssMapping(OutputStream* out,
3123 size_t number_of_indexes,
3124 size_t slot_size,
3125 const BitVector& indexes,
3126 GetBssOffset get_bss_offset) {
3127 // Allocate the IndexBssMapping.
3128 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
3129 number_of_indexes, slot_size, indexes, get_bss_offset);
3130 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
3131 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
3132 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
3133 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
3134 mappings->ClearPadding();
3135 // Encode the IndexBssMapping.
3136 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
3137 auto init_it = mappings->begin();
3138 bool first_index = true;
3139 for (uint32_t index : indexes.Indexes()) {
3140 size_t bss_offset = get_bss_offset(index);
3141 if (first_index) {
3142 first_index = false;
3143 encoder.Reset(index, bss_offset);
3144 } else if (!encoder.TryMerge(index, bss_offset)) {
3145 *init_it = encoder.GetEntry();
3146 ++init_it;
3147 encoder.Reset(index, bss_offset);
3148 }
3149 }
3150 // Store the last entry.
3151 *init_it = encoder.GetEntry();
3152 ++init_it;
3153 DCHECK(init_it == mappings->end());
3154
3155 if (!out->WriteFully(storage.get(), mappings_size)) {
3156 return 0u;
3157 }
3158 return mappings_size;
3159}
3160
3161size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
3162 size_t file_offset,
3163 size_t relative_offset) {
3164 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
3165 if (bss_method_entry_references_.empty() &&
3166 bss_type_entry_references_.empty() &&
3167 bss_string_entry_references_.empty()) {
3168 return relative_offset;
3169 }
3170 // If there are any classes, the class offsets allocation aligns the offset
3171 // and we cannot have method bss mappings without class offsets.
3172 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
3173 "IndexBssMapping alignment check.");
3174 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
3175
3176 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003177 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
3178 const DexFile* dex_file = (*dex_files_)[i];
3179 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00003180 auto method_it = bss_method_entry_references_.find(dex_file);
3181 if (method_it != bss_method_entry_references_.end()) {
3182 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003183 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
3184 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00003185 size_t method_mappings_size = WriteIndexBssMapping(
3186 out,
3187 dex_file->NumMethodIds(),
3188 static_cast<size_t>(pointer_size),
3189 method_indexes,
3190 [=](uint32_t index) {
3191 return bss_method_entries_.Get({dex_file, index});
3192 });
3193 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003194 return 0u;
3195 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003196 size_method_bss_mappings_ += method_mappings_size;
3197 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003198 } else {
3199 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3200 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003201
3202 auto type_it = bss_type_entry_references_.find(dex_file);
3203 if (type_it != bss_type_entry_references_.end()) {
3204 const BitVector& type_indexes = type_it->second;
3205 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3206 DCHECK_OFFSET();
3207 size_t type_mappings_size = WriteIndexBssMapping(
3208 out,
3209 dex_file->NumTypeIds(),
3210 sizeof(GcRoot<mirror::Class>),
3211 type_indexes,
3212 [=](uint32_t index) {
3213 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3214 });
3215 if (type_mappings_size == 0u) {
3216 return 0u;
3217 }
3218 size_type_bss_mappings_ += type_mappings_size;
3219 relative_offset += type_mappings_size;
3220 } else {
3221 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3222 }
3223
3224 auto string_it = bss_string_entry_references_.find(dex_file);
3225 if (string_it != bss_string_entry_references_.end()) {
3226 const BitVector& string_indexes = string_it->second;
3227 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3228 DCHECK_OFFSET();
3229 size_t string_mappings_size = WriteIndexBssMapping(
3230 out,
3231 dex_file->NumStringIds(),
3232 sizeof(GcRoot<mirror::String>),
3233 string_indexes,
3234 [=](uint32_t index) {
3235 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3236 });
3237 if (string_mappings_size == 0u) {
3238 return 0u;
3239 }
3240 size_string_bss_mappings_ += string_mappings_size;
3241 relative_offset += string_mappings_size;
3242 } else {
3243 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3244 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003245 }
3246 return relative_offset;
3247}
3248
3249size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3250 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3251
3252 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3253 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3254 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3255 DCHECK_OFFSET();
3256
3257 // Write OatDexFile.
3258 if (!oat_dex_file->Write(this, out)) {
3259 return 0u;
3260 }
3261 relative_offset += oat_dex_file->SizeOf();
3262 }
3263
3264 return relative_offset;
3265}
3266
3267size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003268 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003269 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003270
Ian Rogers848871b2013-08-05 10:56:33 -07003271 #define DO_TRAMPOLINE(field) \
3272 do { \
3273 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3274 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003275 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003276 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003277 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003278 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003279 return false; \
3280 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003281 size_ ## field += (field)->size(); \
3282 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003283 DCHECK_OFFSET(); \
3284 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003285
Ian Rogers848871b2013-08-05 10:56:33 -07003286 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003287 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003288 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003289 DO_TRAMPOLINE(quick_resolution_trampoline_);
3290 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3291 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003292 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003293 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003294}
3295
Ian Rogers3d504072014-03-01 09:16:49 -08003296size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003297 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003298 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003299 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3300 // As with InitOatCodeDexFiles, also skip the writer if
3301 // compilation was disabled.
3302 if (kOatWriterDebugOatCodeLayout) {
3303 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3304 << this << "), "
3305 << "compilation is disabled";
3306 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003307
Igor Murashkin545412b2017-08-17 15:26:54 -07003308 return relative_offset;
3309 }
3310 ScopedObjectAccess soa(Thread::Current());
3311 DCHECK(ordered_methods_ != nullptr);
3312 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3313 std::move(ordered_methods_);
3314 WriteCodeMethodVisitor visitor(this,
3315 out,
3316 file_offset,
3317 relative_offset,
3318 std::move(*ordered_methods_ptr));
3319 if (UNLIKELY(!visitor.Visit())) {
3320 return 0;
3321 }
3322 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003323
Vladimir Markob163bb72015-03-31 21:49:49 +01003324 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3325 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3326 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3327
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003328 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003329}
3330
Vladimir Marko944da602016-02-19 12:27:55 +00003331bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003332 // Get the elf file offset of the oat file.
3333 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3334 if (raw_file_offset == static_cast<off_t>(-1)) {
3335 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3336 return false;
3337 }
3338 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3339 return true;
3340}
3341
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003342bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003343 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003344
David Brazdil7b49e6c2016-09-01 11:06:18 +01003345 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003346
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003347 only_contains_uncompressed_zip_entries_ = true;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003348 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003349 if (!oat_dex_file.source_.IsZipEntry()) {
3350 only_contains_uncompressed_zip_entries_ = false;
3351 break;
3352 }
3353 ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
3354 if (!entry->IsUncompressed() || !entry->IsAlignedToDexHeader()) {
3355 only_contains_uncompressed_zip_entries_ = false;
3356 break;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003357 }
3358 }
3359
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003360 if (!only_contains_uncompressed_zip_entries_) {
3361 // Write dex files.
3362 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3363 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
3364 return false;
3365 }
3366 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003367
3368 // Write shared dex file data section and fix up the dex file headers.
3369 vdex_dex_shared_data_offset_ = vdex_size_;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003370 uint32_t shared_data_size = 0u;
3371
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003372 if (dex_container_ != nullptr) {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003373 CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003374 DexContainer::Section* const section = dex_container_->GetDataSection();
3375 if (section->Size() > 0) {
3376 const uint32_t shared_data_offset = vdex_size_;
3377 const off_t existing_offset = out->Seek(0, kSeekCurrent);
3378 if (static_cast<uint32_t>(existing_offset) != shared_data_offset) {
3379 LOG(ERROR) << "Expected offset " << shared_data_offset << " but got " << existing_offset;
3380 return false;
3381 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003382 shared_data_size = section->Size();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003383 if (!out->WriteFully(section->Begin(), shared_data_size)) {
3384 LOG(ERROR) << "Failed to write shared data!";
3385 return false;
3386 }
3387 // Fix up the dex headers to have correct offsets to the data section.
3388 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3389 // Overwrite the header by reading it, updating the offset, and writing it back out.
3390 DexFile::Header header;
3391 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3392 LOG(ERROR) << "Failed to read dex header for updating";
3393 return false;
3394 }
3395 CHECK(CompactDexFile::IsMagicValid(header.magic_)) << "Must be compact dex";
3396 CHECK_GT(shared_data_offset, oat_dex_file.dex_file_offset_);
3397 // Offset is from the dex file base.
3398 header.data_off_ = shared_data_offset - oat_dex_file.dex_file_offset_;
3399 // The size should already be what part of the data buffer may be used by the dex.
3400 CHECK_LE(header.data_size_, shared_data_size);
3401 if (!file->PwriteFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3402 LOG(ERROR) << "Failed to write dex header for updating";
3403 return false;
3404 }
3405 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003406 section->Clear();
3407 if (!out->Flush()) {
3408 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
3409 return false;
3410 }
3411 }
3412 dex_container_.reset();
Mathieu Chartierf1609832018-01-31 03:09:56 -08003413 } else {
3414 if (update_input_vdex) {
3415 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3416 DexFile::Header header;
3417 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3418 PLOG(ERROR) << "Failed to read dex header";
3419 return false;
3420 }
3421 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3422 // Non compact dex does not have shared data section.
3423 continue;
3424 }
3425 const uint32_t expected_data_off = vdex_dex_shared_data_offset_ -
3426 oat_dex_file.dex_file_offset_;
3427 if (header.data_off_ != expected_data_off) {
3428 PLOG(ERROR) << "Shared data section offset " << header.data_off_
3429 << " does not match expected value " << expected_data_off;
3430 return false;
3431 }
3432 // The different dex files currently can have different data sizes since
3433 // the dex writer writes them one at a time into the shared section.:w
3434 shared_data_size = std::max(shared_data_size, header.data_size_);
3435 }
3436 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003437 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003438 vdex_size_ += shared_data_size;
3439 size_dex_file_ += shared_data_size;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003440 } else {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003441 vdex_dex_shared_data_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003442 }
3443
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003444 return true;
3445}
3446
3447void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003448 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3449 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3450 }
3451 zipped_dex_files_.clear();
3452 zip_archives_.clear();
3453 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003454}
3455
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003456bool OatWriter::WriteDexFile(OutputStream* out,
3457 File* file,
3458 OatDexFile* oat_dex_file,
3459 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003460 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003461 return false;
3462 }
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003463 // update_input_vdex disables compact dex and layout.
Mathieu Chartier7c6f6362018-01-14 20:24:38 -08003464 if (profile_compilation_info_ != nullptr ||
3465 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
3466 CHECK(!update_input_vdex)
3467 << "We should never update the input vdex when doing dexlayout or compact dex";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003468 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3469 return false;
3470 }
3471 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003472 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003473 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003474 return false;
3475 }
3476 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003477 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003478 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003479 return false;
3480 }
3481 } else {
3482 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003483 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003484 return false;
3485 }
3486 }
3487
3488 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003489 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3490 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003491 size_dex_file_ += oat_dex_file->dex_file_size_;
3492 return true;
3493}
3494
3495bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3496 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003497 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003498 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray67169412018-01-12 09:06:14 +00003499 size_dex_file_alignment_ += start_offset - initial_offset;
Mathieu Chartier7a26f942018-01-04 18:23:55 -08003500
Mathieu Chartier210531f2018-01-12 10:15:51 -08003501 // Leave extra room for the quicken offset table offset.
3502 start_offset += sizeof(VdexFile::QuickeningTableOffsetType);
3503 // TODO: Not count the offset as part of alignment.
3504 size_dex_file_alignment_ += sizeof(VdexFile::QuickeningTableOffsetType);
3505
3506 size_t file_offset = start_offset;
3507
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003508 // Seek to the start of the dex file and flush any pending operations in the stream.
3509 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003510 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3511 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003512 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003513 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003514 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3515 return false;
3516 }
3517 if (!out->Flush()) {
3518 PLOG(ERROR) << "Failed to flush before writing dex file."
3519 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3520 return false;
3521 }
3522 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003523 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003524 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003525 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003526 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3527 return false;
3528 }
3529
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003530 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003531 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003532 return true;
3533}
3534
Jeff Hao608f2ce2016-10-19 11:17:11 -07003535bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
David Brazdil2b9c35b2018-01-12 15:44:43 +00003536 // Open dex files and write them into `out`.
3537 // Note that we only verify dex files which do not belong to the boot class path.
3538 // This is because those have been processed by `hiddenapi` and would not pass
3539 // some of the checks. No guarantees are lost, however, as `hiddenapi` verifies
3540 // the dex files prior to processing.
Jeff Hao608f2ce2016-10-19 11:17:11 -07003541 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3542 std::string error_msg;
3543 std::string location(oat_dex_file->GetLocation());
3544 std::unique_ptr<const DexFile> dex_file;
David Sehr013fd802018-01-11 22:55:24 -08003545 const ArtDexFileLoader dex_file_loader;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003546 if (oat_dex_file->source_.IsZipEntry()) {
3547 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3548 std::unique_ptr<MemMap> mem_map(
3549 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003550 if (mem_map == nullptr) {
3551 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3552 return false;
3553 }
David Sehr013fd802018-01-11 22:55:24 -08003554 dex_file = dex_file_loader.Open(location,
3555 zip_entry->GetCrc32(),
3556 std::move(mem_map),
David Brazdil2b9c35b2018-01-12 15:44:43 +00003557 /* verify */ !compiling_boot_image_,
David Sehr013fd802018-01-11 22:55:24 -08003558 /* verify_checksum */ true,
3559 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003560 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003561 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003562 int dup_fd = dup(raw_file->Fd());
3563 if (dup_fd < 0) {
3564 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3565 return false;
3566 }
David Brazdil2b9c35b2018-01-12 15:44:43 +00003567 dex_file = dex_file_loader.OpenDex(dup_fd, location,
3568 /* verify */ !compiling_boot_image_,
3569 /* verify_checksum */ true,
3570 /* mmap_shared */ false,
3571 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003572 } else {
3573 // The source data is a vdex file.
3574 CHECK(oat_dex_file->source_.IsRawData())
3575 << static_cast<size_t>(oat_dex_file->source_.GetType());
3576 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3577 // Note: The raw data has already been checked to contain the header
3578 // and all the data that the header specifies as the file size.
3579 DCHECK(raw_dex_file != nullptr);
3580 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3581 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3582 // Since the source may have had its layout changed, or may be quickened, don't verify it.
David Sehr013fd802018-01-11 22:55:24 -08003583 dex_file = dex_file_loader.Open(raw_dex_file,
3584 header->file_size_,
3585 location,
3586 oat_dex_file->dex_file_location_checksum_,
3587 nullptr,
3588 /* verify */ false,
3589 /* verify_checksum */ false,
3590 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003591 }
Jeff Haode197542017-02-03 10:48:13 -08003592 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003593 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003594 return false;
3595 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003596 Options options;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003597 options.compact_dex_level_ = compact_dex_level_;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003598 options.update_checksum_ = true;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -08003599 DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003600 const uint8_t* dex_src = nullptr;
3601 if (dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0, &dex_container_, &error_msg)) {
3602 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3603 // Dex layout can affect the size of the dex file, so we update here what we have set
3604 // when adding the dex file as a source.
3605 const UnalignedDexFileHeader* header =
3606 AsUnalignedDexFileHeader(dex_container_->GetMainSection()->Begin());
3607 oat_dex_file->dex_file_size_ = header->file_size_;
3608 dex_src = dex_container_->GetMainSection()->Begin();
3609 } else {
3610 LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
3611 // Since we failed to convert the dex, just copy the input dex.
3612 dex_src = dex_file->Begin();
3613 }
3614 if (!WriteDexFile(out, oat_dex_file, dex_src, /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003615 return false;
3616 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003617 if (dex_container_ != nullptr) {
3618 // Clear the main section in case we write more data into the container.
3619 dex_container_->GetMainSection()->Clear();
3620 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003621 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003622 return true;
3623}
3624
David Brazdil7b49e6c2016-09-01 11:06:18 +01003625bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003626 File* file,
3627 OatDexFile* oat_dex_file,
3628 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003629 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003630 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003631
3632 // Extract the dex file and get the extracted size.
3633 std::string error_msg;
3634 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3635 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3636 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3637 return false;
3638 }
3639 if (file->Flush() != 0) {
3640 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3641 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3642 return false;
3643 }
3644 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3645 if (extracted_end == static_cast<off_t>(-1)) {
3646 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3647 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3648 return false;
3649 }
3650 if (extracted_end < static_cast<off_t>(start_offset)) {
3651 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3652 << " Start: " << start_offset
3653 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3654 return false;
3655 }
3656 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3657 if (extracted_size < sizeof(DexFile::Header)) {
3658 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3659 << extracted_size << " File: " << oat_dex_file->GetLocation();
3660 return false;
3661 }
3662
3663 // Read the dex file header and extract required data to OatDexFile.
3664 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3665 if (actual_offset != static_cast<off_t>(start_offset)) {
3666 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3667 << " Expected: " << start_offset
3668 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3669 return false;
3670 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003671 if (extracted_size < oat_dex_file->dex_file_size_) {
3672 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3673 << " file size from header: " << oat_dex_file->dex_file_size_
3674 << " File: " << oat_dex_file->GetLocation();
3675 return false;
3676 }
3677
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003678 // Seek both file and stream to the end offset.
3679 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3680 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3681 if (actual_offset != static_cast<off_t>(end_offset)) {
3682 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3683 << " Expected: " << end_offset
3684 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3685 return false;
3686 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003687 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003688 if (actual_offset != static_cast<off_t>(end_offset)) {
3689 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3690 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3691 return false;
3692 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003693 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003694 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3695 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3696 return false;
3697 }
3698
3699 // If we extracted more than the size specified in the header, truncate the file.
3700 if (extracted_size > oat_dex_file->dex_file_size_) {
3701 if (file->SetLength(end_offset) != 0) {
3702 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003703 << " File: " << oat_dex_file->GetLocation()
3704 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003705 return false;
3706 }
3707 }
3708
3709 return true;
3710}
3711
David Brazdil7b49e6c2016-09-01 11:06:18 +01003712bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003713 File* file,
3714 OatDexFile* oat_dex_file,
3715 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003716 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003717 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003718
3719 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3720 if (input_offset != static_cast<off_t>(0)) {
3721 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3722 << " Expected: 0"
3723 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3724 return false;
3725 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003726
3727 // Copy the input dex file using sendfile().
3728 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3729 PLOG(ERROR) << "Failed to copy dex file to oat file."
3730 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3731 return false;
3732 }
3733 if (file->Flush() != 0) {
3734 PLOG(ERROR) << "Failed to flush dex file."
3735 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3736 return false;
3737 }
3738
3739 // Check file position and seek the stream to the end offset.
3740 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3741 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3742 if (actual_offset != static_cast<off_t>(end_offset)) {
3743 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3744 << " Expected: " << end_offset
3745 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3746 return false;
3747 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003748 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003749 if (actual_offset != static_cast<off_t>(end_offset)) {
3750 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3751 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3752 return false;
3753 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003754 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003755 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3756 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3757 return false;
3758 }
3759
3760 return true;
3761}
3762
David Brazdil7b49e6c2016-09-01 11:06:18 +01003763bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003764 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003765 const uint8_t* dex_file,
3766 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003767 // Note: The raw data has already been checked to contain the header
3768 // and all the data that the header specifies as the file size.
3769 DCHECK(dex_file != nullptr);
3770 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3771 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3772
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003773 if (update_input_vdex) {
3774 // The vdex already contains the dex code, no need to write it again.
3775 } else {
3776 if (!out->WriteFully(dex_file, header->file_size_)) {
3777 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3778 << " to " << out->GetLocation();
3779 return false;
3780 }
3781 if (!out->Flush()) {
3782 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3783 << " File: " << oat_dex_file->GetLocation();
3784 return false;
3785 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003786 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003787 return true;
3788}
3789
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003790bool OatWriter::OpenDexFiles(
3791 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003792 bool verify,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003793 /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003794 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3795 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3796
3797 if (oat_dex_files_.empty()) {
3798 // Nothing to do.
3799 return true;
3800 }
3801
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003802 if (only_contains_uncompressed_zip_entries_) {
3803 std::vector<std::unique_ptr<const DexFile>> dex_files;
3804 std::vector<std::unique_ptr<MemMap>> maps;
3805 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3806 std::string error_msg;
3807 MemMap* map = oat_dex_file.source_.GetZipEntry()->MapDirectlyFromFile(
3808 oat_dex_file.dex_file_location_data_, &error_msg);
3809 if (map == nullptr) {
3810 LOG(ERROR) << error_msg;
3811 return false;
3812 }
3813 maps.emplace_back(map);
3814 // Now, open the dex file.
3815 const ArtDexFileLoader dex_file_loader;
3816 dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
3817 map->Size(),
3818 oat_dex_file.GetLocation(),
3819 oat_dex_file.dex_file_location_checksum_,
3820 /* oat_dex_file */ nullptr,
3821 verify,
3822 verify,
3823 &error_msg));
3824 if (dex_files.back() == nullptr) {
3825 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3826 << " Error: " << error_msg;
3827 return false;
3828 }
3829 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3830 }
3831 *opened_dex_files_map = std::move(maps);
3832 *opened_dex_files = std::move(dex_files);
3833 CloseSources();
3834 return true;
3835 }
3836 // We could have closed the sources at the point of writing the dex files, but to
3837 // make it consistent with the case we're not writing the dex files, we close them now.
3838 CloseSources();
3839
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003840 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003841 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003842
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003843 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003844 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3845 length,
3846 PROT_READ | PROT_WRITE,
3847 MAP_SHARED,
3848 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003849 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003850 /* low_4gb */ false,
3851 file->GetPath().c_str(),
3852 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003853 if (dex_files_map == nullptr) {
3854 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3855 << " error: " << error_msg;
3856 return false;
3857 }
David Sehr013fd802018-01-11 22:55:24 -08003858 const ArtDexFileLoader dex_file_loader;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003859 std::vector<std::unique_ptr<const DexFile>> dex_files;
3860 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003861 const uint8_t* raw_dex_file =
3862 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003863
3864 if (kIsDebugBuild) {
3865 // Sanity check our input files.
3866 // Note that ValidateDexFileHeader() logs error messages.
3867 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3868 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003869 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3870 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003871
3872 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3873 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3874 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003875 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3876 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003877 }
3878
3879 // Now, open the dex file.
David Sehr013fd802018-01-11 22:55:24 -08003880 dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
3881 oat_dex_file.dex_file_size_,
3882 oat_dex_file.GetLocation(),
3883 oat_dex_file.dex_file_location_checksum_,
3884 /* oat_dex_file */ nullptr,
3885 verify,
3886 verify,
3887 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003888 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003889 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3890 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003891 return false;
3892 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003893
3894 // Set the class_offsets size now that we have easy access to the DexFile and
David Sehr013fd802018-01-11 22:55:24 -08003895 // it has been verified in dex_file_loader.Open.
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003896 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003897 }
3898
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003899 opened_dex_files_map->push_back(std::move(dex_files_map));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003900 *opened_dex_files = std::move(dex_files);
3901 return true;
3902}
3903
3904bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003905 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003906 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3907 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3908
David Brazdil7b49e6c2016-09-01 11:06:18 +01003909 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3910 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3911 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3912 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3913 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3914 return false;
3915 }
3916
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003917 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3918 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3919 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003920 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3921
3922 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3923 oat_dex_file->class_offsets_.empty()) {
3924 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003925 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003926
3927 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3928 if (table_size == 0u) {
3929 continue;
3930 }
3931
3932 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003933 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003934 const DexFile& dex_file = *opened_dex_files[i];
3935 {
3936 std::unique_ptr<TypeLookupTable> type_lookup_table =
3937 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3938 type_lookup_table_oat_dex_files_.push_back(
3939 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3940 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3941 }
3942 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003943
3944 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003945 size_t initial_offset = oat_size_;
3946 size_t rodata_offset = RoundUp(initial_offset, 4);
3947 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003948
3949 if (padding_size != 0u) {
3950 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003951 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003952 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3953 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003954 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003955 return false;
3956 }
3957 }
3958
3959 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003960 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003961 DCHECK_EQ(table_size, table->RawDataLength());
3962
David Brazdil7b49e6c2016-09-01 11:06:18 +01003963 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003964 PLOG(ERROR) << "Failed to write lookup table."
3965 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003966 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003967 return false;
3968 }
3969
3970 oat_dex_file->lookup_table_offset_ = rodata_offset;
3971
David Brazdil7b49e6c2016-09-01 11:06:18 +01003972 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003973 size_oat_lookup_table_ += table_size;
3974 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003975 }
3976
David Brazdil7b49e6c2016-09-01 11:06:18 +01003977 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003978 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003979 << " File: " << oat_rodata->GetLocation();
3980 return false;
3981 }
3982
3983 return true;
3984}
3985
Mathieu Chartier120aa282017-08-05 16:03:03 -07003986bool OatWriter::WriteDexLayoutSections(
3987 OutputStream* oat_rodata,
3988 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3989 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3990
3991 if (!kWriteDexLayoutInfo) {
3992 return true;;
3993 }
3994
3995 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3996 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3997 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3998 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3999 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
4000 return false;
4001 }
4002
4003 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
4004 size_t rodata_offset = oat_size_;
4005 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
4006 OatDexFile* oat_dex_file = &oat_dex_files_[i];
4007 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
4008
4009 // Write dex layout section alignment bytes.
4010 const size_t padding_size =
4011 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
4012 if (padding_size != 0u) {
4013 std::vector<uint8_t> buffer(padding_size, 0u);
4014 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
4015 PLOG(ERROR) << "Failed to write lookup table alignment padding."
4016 << " File: " << oat_dex_file->GetLocation()
4017 << " Output: " << oat_rodata->GetLocation();
4018 return false;
4019 }
4020 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
4021 rodata_offset += padding_size;
4022 }
4023
4024 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
4025 DCHECK_EQ(oat_data_offset_ + rodata_offset,
4026 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
4027 DCHECK(oat_dex_file != nullptr);
4028 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
4029 sizeof(oat_dex_file->dex_sections_layout_))) {
4030 PLOG(ERROR) << "Failed to write dex layout sections."
4031 << " File: " << oat_dex_file->GetLocation()
4032 << " Output: " << oat_rodata->GetLocation();
4033 return false;
4034 }
4035 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
4036 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
4037 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
4038 }
4039 oat_size_ = rodata_offset;
4040
4041 if (!oat_rodata->Flush()) {
4042 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
4043 << " File: " << oat_rodata->GetLocation();
4044 return false;
4045 }
4046
4047 return true;
4048}
4049
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004050bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004051 // Write checksums
4052 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
4053 if (actual_offset != sizeof(VdexFile::Header)) {
4054 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
4055 << " File: " << vdex_out->GetLocation();
4056 return false;
4057 }
4058
4059 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
4060 OatDexFile* oat_dex_file = &oat_dex_files_[i];
4061 if (!vdex_out->WriteFully(
4062 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
4063 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
4064 << vdex_out->GetLocation();
4065 return false;
4066 }
4067 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
4068 }
4069
4070 // Write header.
4071 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01004072 if (actual_offset != 0) {
4073 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
4074 << " File: " << vdex_out->GetLocation();
4075 return false;
4076 }
4077
David Brazdil5d5a36b2016-09-14 15:34:10 +01004078 DCHECK_NE(vdex_dex_files_offset_, 0u);
4079 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
David Brazdil93592f52017-12-08 10:53:27 +00004080 DCHECK_NE(vdex_quickening_info_offset_, 0u);
David Brazdil5d5a36b2016-09-14 15:34:10 +01004081
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08004082 size_t dex_section_size = vdex_dex_shared_data_offset_ - vdex_dex_files_offset_;
4083 size_t dex_shared_data_size = vdex_verifier_deps_offset_ - vdex_dex_shared_data_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01004084 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
4085 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01004086
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004087 VdexFile::Header vdex_header(oat_dex_files_.size(),
4088 dex_section_size,
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08004089 dex_shared_data_size,
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004090 verifier_deps_section_size,
4091 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01004092 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
4093 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004094 return false;
4095 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004096 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004097
David Brazdil5d5a36b2016-09-14 15:34:10 +01004098 if (!vdex_out->Flush()) {
4099 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
4100 << " File: " << vdex_out->GetLocation();
4101 return false;
4102 }
4103
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004104 return true;
4105}
4106
Vladimir Markof4da6752014-08-01 19:04:18 +01004107bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004108 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
4109}
4110
4111bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004112 static const uint8_t kPadding[] = {
4113 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
4114 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004115 DCHECK_LE(size, sizeof(kPadding));
4116 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004117 return false;
4118 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004119 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01004120 return true;
4121}
4122
Vladimir Marko944da602016-02-19 12:27:55 +00004123void OatWriter::SetMultiOatRelativePatcherAdjustment() {
4124 DCHECK(dex_files_ != nullptr);
4125 DCHECK(relative_patcher_ != nullptr);
4126 DCHECK_NE(oat_data_offset_, 0u);
4127 if (image_writer_ != nullptr && !dex_files_->empty()) {
4128 // The oat data begin may not be initialized yet but the oat file offset is ready.
4129 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
4130 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
4131 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01004132 }
4133}
4134
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004135OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
4136 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004137 CreateTypeLookupTable create_type_lookup_table,
4138 uint32_t dex_file_location_checksum,
4139 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004140 : source_(source),
4141 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004142 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004143 offset_(0),
4144 dex_file_location_size_(strlen(dex_file_location)),
4145 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004146 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004147 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004148 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004149 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00004150 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00004151 type_bss_mapping_offset_(0u),
4152 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004153 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004154 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07004155}
4156
4157size_t OatWriter::OatDexFile::SizeOf() const {
4158 return sizeof(dex_file_location_size_)
4159 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08004160 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08004161 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004162 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004163 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004164 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00004165 + sizeof(type_bss_mapping_offset_)
4166 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004167 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004168}
4169
4170bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
4171 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08004172 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004173
Vladimir Markoe079e212016-05-25 12:49:49 +01004174 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004175 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004176 return false;
4177 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004178 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004179
Vladimir Markoe079e212016-05-25 12:49:49 +01004180 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004181 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004182 return false;
4183 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004184 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004185
Vladimir Markoe079e212016-05-25 12:49:49 +01004186 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004187 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004188 return false;
4189 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004190 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004191
Vladimir Markoe079e212016-05-25 12:49:49 +01004192 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004193 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08004194 return false;
4195 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004196 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004197
Vladimir Markoe079e212016-05-25 12:49:49 +01004198 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004199 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
4200 return false;
4201 }
4202 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
4203
Vladimir Markoe079e212016-05-25 12:49:49 +01004204 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03004205 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
4206 return false;
4207 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004208 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004209
Mathieu Chartier120aa282017-08-05 16:03:03 -07004210 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4211 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4212 return false;
4213 }
4214 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4215
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004216 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4217 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4218 return false;
4219 }
4220 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4221
Vladimir Markof3c52b42017-11-17 17:32:12 +00004222 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4223 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4224 return false;
4225 }
4226 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4227
4228 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4229 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4230 return false;
4231 }
4232 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4233
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004234 return true;
4235}
4236
4237bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004238 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004239 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4240 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004241 return false;
4242 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004243 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004244 return true;
4245}
4246
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004247OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004248 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004249 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004250 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004251 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004252 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004253
Brian Carlstromba150c32013-08-27 17:31:03 -07004254 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4255
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004256 method_offsets_.resize(compiled_methods_with_code);
4257 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004258
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004259 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4260 // We only create this instance if there are at least some compiled.
4261 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004262 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004263 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4264 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4265 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4266 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004267 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004268 method_bitmap_size_ = 0;
4269 }
4270
4271 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004272 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004273 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004274 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4275 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004276 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004277 method_bitmap_->SetBit(i);
4278 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004279 } else {
4280 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004281 }
4282 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004283}
4284
Brian Carlstrom265091e2013-01-30 14:08:26 -08004285size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004286 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004287 + method_bitmap_size_
4288 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004289}
4290
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004291bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4292 OutputStream* out,
4293 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004294 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004295 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004296 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004297 return false;
4298 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004299 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004300
Vladimir Markoe079e212016-05-25 12:49:49 +01004301 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004302 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004303 return false;
4304 }
4305 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004306 return true;
4307}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004308
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004309bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004310 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004311 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004312 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004313 return false;
4314 }
4315 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004316
Vladimir Markoe079e212016-05-25 12:49:49 +01004317 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004318 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004319 return false;
4320 }
4321 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4322 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004323
Vladimir Markoe079e212016-05-25 12:49:49 +01004324 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004325 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004326 return false;
4327 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004328 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004329 return true;
4330}
4331
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004332const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
4333 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004334 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004335 uint32_t utf16_length;
4336 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
4337 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
4338 InternTable::Utf8String string(utf16_length,
4339 utf8_data,
4340 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
4341 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
4342 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
4343 auto it = table.Find(string);
4344 if (it != table.end()) {
4345 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4346 }
4347 }
4348 LOG(FATAL) << "Did not find boot image string " << utf8_data;
4349 UNREACHABLE();
4350}
4351
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004352const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
4353 dex::TypeIndex type_idx)
4354 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
4355 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
4356 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
4357 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
4358 for (const ClassTable::ClassSet& class_set : table->classes_) {
4359 auto it = class_set.Find(pair);
4360 if (it != class_set.end()) {
4361 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4362 }
4363 }
4364 LOG(FATAL) << "Did not find boot image class " << descriptor;
4365 UNREACHABLE();
4366}
4367
David Srbecky32210b92017-12-04 14:39:21 +00004368debug::DebugInfo OatWriter::GetDebugInfo() const {
4369 debug::DebugInfo debug_info{};
4370 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
David Srbecky96c84462018-02-05 15:42:40 +00004371 if (VdexWillContainDexFiles()) {
David Srbecky25931622018-01-18 22:55:20 +00004372 DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
4373 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
4374 const DexFile* dex_file = (*dex_files_)[i];
4375 const OatDexFile& oat_dex_file = oat_dex_files_[i];
David Srbecky96c84462018-02-05 15:42:40 +00004376 uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
4377 if (dex_file_offset != 0) {
4378 debug_info.dex_files.emplace(dex_file_offset, dex_file);
4379 }
David Srbecky32210b92017-12-04 14:39:21 +00004380 }
4381 }
4382 return debug_info;
4383}
4384
Vladimir Marko74527972016-11-29 15:57:32 +00004385} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004386} // namespace art