blob: 690b565090ccdf6161529fce0e7a08fb30d5c52d [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
David Sehrc431b9d2018-03-02 12:01:51 -080030#include "base/os.h"
David Sehr67bf42e2018-02-26 16:43:04 -080031#include "base/safe_map.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080032#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080033#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070034#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010035#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010036#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000037#include "debug/method_debug_info.h"
David Sehr013fd802018-01-11 22:55:24 -080038#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080039#include "dex/dex_file-inl.h"
40#include "dex/dex_file_loader.h"
41#include "dex/dex_file_types.h"
42#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070043#include "dex/type_lookup_table.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000044#include "dex/verification_results.h"
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080045#include "dex_container.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070046#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070047#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000048#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010049#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010052#include "image_writer.h"
Andreas Gampe3913e482018-01-22 18:58:01 -080053#include "jit/profile_compilation_info.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010054#include "linker/buffered_output_stream.h"
55#include "linker/file_output_stream.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000056#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010057#include "linker/linker_patch.h"
Vladimir Marko944da602016-02-19 12:27:55 +000058#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000059#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/array.h"
61#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010062#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070063#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010064#include "oat_quick_method_header.h"
Mathieu Chartier210531f2018-01-12 10:15:51 -080065#include "quicken_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070066#include "scoped_thread_state_change-inl.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),
Mathieu Chartier792111c2018-02-15 13:02:15 -0800371 extract_dex_files_into_vdex_(true),
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),
Vladimir Markob066d432018-01-03 13:14:37 +0000378 code_size_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100379 oat_size_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000380 data_bimg_rel_ro_start_(0u),
381 data_bimg_rel_ro_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000382 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000383 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100384 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000385 bss_roots_offset_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000386 data_bimg_rel_ro_entries_(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100387 bss_method_entry_references_(),
388 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000389 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000390 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100391 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700392 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100393 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000394 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700395 size_dex_file_alignment_(0),
396 size_executable_offset_alignment_(0),
397 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700398 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700399 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100400 size_verifier_deps_(0),
401 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100402 size_quickening_info_(0),
403 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700404 size_interpreter_to_interpreter_bridge_(0),
405 size_interpreter_to_compiled_code_bridge_(0),
406 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800407 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700408 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700409 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700410 size_quick_to_interpreter_bridge_(0),
411 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100412 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700413 size_code_(0),
414 size_code_alignment_(0),
Vladimir Markob066d432018-01-03 13:14:37 +0000415 size_data_bimg_rel_ro_(0),
416 size_data_bimg_rel_ro_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100417 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100418 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700419 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700420 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700421 size_oat_dex_file_location_size_(0),
422 size_oat_dex_file_location_data_(0),
423 size_oat_dex_file_location_checksum_(0),
424 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000425 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000426 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700427 size_oat_dex_file_dex_layout_sections_offset_(0),
428 size_oat_dex_file_dex_layout_sections_(0),
429 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100430 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000431 size_oat_dex_file_type_bss_mapping_offset_(0),
432 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000433 size_oat_lookup_table_alignment_(0),
434 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000435 size_oat_class_offsets_alignment_(0),
436 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700437 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700438 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700439 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100440 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100441 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000442 size_type_bss_mappings_(0u),
443 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000444 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700445 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700446 profile_compilation_info_(info),
447 compact_dex_level_(compact_dex_level) {
Mathieu Chartierddf39552018-04-03 10:22:27 -0700448 // If we have a profile, always use at least the default compact dex level. The reason behind
449 // this is that CompactDex conversion is not more expensive than normal dexlayout.
450 if (info != nullptr && compact_dex_level_ == CompactDexLevel::kCompactDexLevelNone) {
451 compact_dex_level_ = kDefaultCompactDexLevel;
452 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000453}
454
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000455static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
456 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
457 if (!valid_standard_dex_magic) {
458 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
459 return false;
460 }
461 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
462 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
463 return false;
464 }
465 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
466 if (header->file_size_ < sizeof(DexFile::Header)) {
467 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
468 << " File: " << location;
469 return false;
470 }
471 return true;
472}
473
474static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
475 uint8_t* raw_header,
476 const char* location) {
477 // Read the dex file header and perform minimal verification.
478 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
479 PLOG(ERROR) << "Failed to read dex file header. Actual: "
480 << " File: " << location << " Output: " << file->GetPath();
481 return nullptr;
482 }
483 if (!ValidateDexFileHeader(raw_header, location)) {
484 return nullptr;
485 }
486
487 return AsUnalignedDexFileHeader(raw_header);
488}
489
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490bool OatWriter::AddDexFileSource(const char* filename,
491 const char* location,
492 CreateTypeLookupTable create_type_lookup_table) {
493 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
494 uint32_t magic;
495 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700496 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
497 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000498 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
499 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700500 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000501 uint8_t raw_header[sizeof(DexFile::Header)];
502 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
503 if (header == nullptr) {
504 return false;
505 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000506 // The file is open for reading, not writing, so it's OK to let the File destructor
507 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700508 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000509 oat_dex_files_.emplace_back(/* OatDexFile */
510 location,
511 DexFileSource(raw_dex_files_.back().get()),
512 create_type_lookup_table,
513 header->checksum_,
514 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000515 } else if (IsZipMagic(magic)) {
516 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
517 return false;
518 }
519 } else {
520 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
521 return false;
522 }
523 return true;
524}
525
526// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700527bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000528 const char* location,
529 CreateTypeLookupTable create_type_lookup_table) {
530 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
531 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700532 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000533 ZipArchive* zip_archive = zip_archives_.back().get();
534 if (zip_archive == nullptr) {
535 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
536 << error_msg;
537 return false;
538 }
539 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700540 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000541 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
542 if (entry == nullptr) {
543 break;
544 }
545 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700546 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000547 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000548 // We override the checksum from header with the CRC from ZIP entry.
549 oat_dex_files_.emplace_back(/* OatDexFile */
550 full_location,
551 DexFileSource(zipped_dex_files_.back().get()),
552 create_type_lookup_table,
553 zipped_dex_files_.back()->GetCrc32(),
554 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000555 }
556 if (zipped_dex_file_locations_.empty()) {
557 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
558 return false;
559 }
560 return true;
561}
562
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000563// Add dex file source(s) from a vdex file specified by a file handle.
564bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
565 const char* location,
566 CreateTypeLookupTable create_type_lookup_table) {
567 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000568 DCHECK(vdex_file.HasDexSection());
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000569 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000570 for (size_t i = 0; i < vdex_file.GetVerifierDepsHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000571 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
572 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000573 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
574 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000575 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700576
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700577 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000578 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
579 return false;
580 }
581 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700582 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000583 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000584 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
585 oat_dex_files_.emplace_back(/* OatDexFile */
586 full_location,
587 DexFileSource(current_dex_data),
588 create_type_lookup_table,
589 vdex_file.GetLocationChecksum(i),
590 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000591 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000592
593 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
594 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
595 return false;
596 }
597
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000598 if (oat_dex_files_.empty()) {
599 LOG(ERROR) << "No dex files in vdex file created from " << location;
600 return false;
601 }
602 return true;
603}
604
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000605// Add dex file source from raw memory.
606bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
607 const char* location,
608 uint32_t location_checksum,
609 CreateTypeLookupTable create_type_lookup_table) {
610 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
611 if (data.size() < sizeof(DexFile::Header)) {
612 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
613 << data.size() << " File: " << location;
614 return false;
615 }
616 if (!ValidateDexFileHeader(data.data(), location)) {
617 return false;
618 }
619 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
620 if (data.size() < header->file_size_) {
621 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
622 << " file size from header: " << header->file_size_ << " File: " << location;
623 return false;
624 }
625
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000626 oat_dex_files_.emplace_back(/* OatDexFile */
627 location,
628 DexFileSource(data.data()),
629 create_type_lookup_table,
630 location_checksum,
631 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000632 return true;
633}
634
Calin Juravle1ce70852017-06-28 10:59:03 -0700635dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
636 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000637 locations.reserve(oat_dex_files_.size());
638 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
639 locations.push_back(oat_dex_file.GetLocation());
640 }
641 return locations;
642}
643
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700644bool OatWriter::MayHaveCompiledMethods() const {
645 return CompilerFilter::IsAnyCompilationEnabled(
646 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
647}
648
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000649bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100650 File* vdex_file,
651 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000652 InstructionSet instruction_set,
653 const InstructionSetFeatures* instruction_set_features,
654 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800655 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000656 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +0000657 CopyOption copy_dex_files,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000658 /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000659 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
660 CHECK(write_state_ == WriteState::kAddingDexFileSources);
661
David Brazdil7b49e6c2016-09-01 11:06:18 +0100662 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
663 if (!RecordOatDataOffset(oat_rodata)) {
664 return false;
665 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000666
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000667 std::vector<std::unique_ptr<MemMap>> dex_files_map;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000668 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100669
670 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000671
672 // Reserve space for Vdex header and checksums.
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000673 vdex_size_ = sizeof(VdexFile::VerifierDepsHeader) +
674 oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100675 oat_size_ = InitOatHeader(instruction_set,
676 instruction_set_features,
677 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
678 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100679
680 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
681
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000682 std::unique_ptr<BufferedOutputStream> vdex_out =
683 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
684 // Write DEX files into VDEX, mmap and open them.
Mathieu Chartier792111c2018-02-15 13:02:15 -0800685 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex, copy_dex_files) ||
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000686 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
687 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000688 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000689
Mathieu Chartier120aa282017-08-05 16:03:03 -0700690 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000691 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
692 return false;
693 }
694
Mathieu Chartier120aa282017-08-05 16:03:03 -0700695 // Write dex layout sections into the oat file.
696 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
697 return false;
698 }
699
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000700 *opened_dex_files_map = std::move(dex_files_map);
701 *opened_dex_files = std::move(dex_files);
702 write_state_ = WriteState::kPrepareLayout;
703 return true;
704}
705
Vladimir Marko74527972016-11-29 15:57:32 +0000706void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000707 CHECK(write_state_ == WriteState::kPrepareLayout);
708
Vladimir Marko944da602016-02-19 12:27:55 +0000709 relative_patcher_ = relative_patcher;
710 SetMultiOatRelativePatcherAdjustment();
711
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000712 if (compiling_boot_image_) {
713 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800714 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100715 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000716 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100717
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100718 {
719 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
720 InitBssLayout(instruction_set);
721 }
722
David Brazdil7b49e6c2016-09-01 11:06:18 +0100723 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800724 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100725 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
726 offset = InitClassOffsets(offset);
727 }
728 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000729 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800730 offset = InitOatClasses(offset);
731 }
732 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000733 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
734 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100735 }
736 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000737 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100738 offset = InitOatMaps(offset);
739 }
740 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100741 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
742 oat_header_->SetOatDexFilesOffset(offset);
743 offset = InitOatDexFiles(offset);
744 }
745 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000746 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800747 offset = InitOatCode(offset);
748 }
749 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000750 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800751 offset = InitOatCodeDexFiles(offset);
Vladimir Markob066d432018-01-03 13:14:37 +0000752 code_size_ = offset - GetOatHeader().GetExecutableOffset();
Ian Rogersca368cb2013-11-15 15:52:08 -0800753 }
Vladimir Markob066d432018-01-03 13:14:37 +0000754 {
755 TimingLogger::ScopedTiming split("InitDataBimgRelRoLayout", timings_);
756 offset = InitDataBimgRelRoLayout(offset);
757 }
758 oat_size_ = offset; // .bss does not count towards oat_size_.
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100759 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100760
Brian Carlstrome24fa612011-09-29 00:53:55 -0700761 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800762 if (compiling_boot_image_) {
763 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000764 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800765 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000766
767 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700768}
769
Ian Rogers0571d352011-11-03 19:51:38 -0700770OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700771}
772
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100773class OatWriter::DexMethodVisitor {
774 public:
775 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100776 : writer_(writer),
777 offset_(offset),
778 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700779 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100780
781 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
782 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700783 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100784 dex_file_ = dex_file;
785 class_def_index_ = class_def_index;
786 return true;
787 }
788
789 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
790
791 virtual bool EndClass() {
792 if (kIsDebugBuild) {
793 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700794 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100795 }
796 return true;
797 }
798
799 size_t GetOffset() const {
800 return offset_;
801 }
802
803 protected:
804 virtual ~DexMethodVisitor() { }
805
806 OatWriter* const writer_;
807
808 // The offset is usually advanced for each visited method by the derived class.
809 size_t offset_;
810
811 // The dex file and class def index are set in StartClass().
812 const DexFile* dex_file_;
813 size_t class_def_index_;
814};
815
816class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
817 public:
818 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100819 : DexMethodVisitor(writer, offset),
820 oat_class_index_(0u),
821 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100822
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100823 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100824 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700825 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
826 // There are no oat classes if there aren't any compiled methods.
827 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
828 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100829 method_offsets_index_ = 0u;
830 return true;
831 }
832
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100833 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100834 ++oat_class_index_;
835 return DexMethodVisitor::EndClass();
836 }
837
838 protected:
839 size_t oat_class_index_;
840 size_t method_offsets_index_;
841};
842
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100843static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000844 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100845}
846
847static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000848 // The dextodexcompiler puts the quickening info table into the CompiledMethod
849 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100850 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
851}
852
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100853class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
854 public:
855 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
856 : DexMethodVisitor(writer, /* offset */ 0u) {}
857
858 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
859 const ClassDataItemIterator& it) OVERRIDE {
860 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
861 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
862 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100863 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100864 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Markob066d432018-01-03 13:14:37 +0000865 if (patch.GetType() == LinkerPatch::Type::kDataBimgRelRo) {
866 writer_->data_bimg_rel_ro_entries_.Overwrite(patch.BootImageOffset(),
867 /* placeholder */ 0u);
868 } else if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100869 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000870 AddBssReference(target_method,
871 target_method.dex_file->NumMethodIds(),
872 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100873 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
874 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000875 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
876 AddBssReference(target_type,
877 target_type.dex_file->NumTypeIds(),
878 &writer_->bss_type_entry_references_);
879 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100880 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000881 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
882 AddBssReference(target_string,
883 target_string.dex_file->NumStringIds(),
884 &writer_->bss_string_entry_references_);
885 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100886 }
887 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100888 } else {
889 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100890 }
891 return true;
892 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000893
894 private:
895 void AddBssReference(const DexFileReference& ref,
896 size_t number_of_indexes,
897 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
898 // We currently support inlining of throwing instructions only when they originate in the
899 // same dex file as the outer method. All .bss references are used by throwing instructions.
900 DCHECK_EQ(dex_file_, ref.dex_file);
901
902 auto refs_it = references->find(ref.dex_file);
903 if (refs_it == references->end()) {
904 refs_it = references->Put(
905 ref.dex_file,
906 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
907 refs_it->second.ClearAllBits();
908 }
909 refs_it->second.SetBit(ref.index);
910 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100911};
912
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100913class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
914 public:
915 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100916 : DexMethodVisitor(writer, offset),
917 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100918 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000919 size_t num_classes = 0u;
920 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
921 num_classes += oat_dex_file.class_offsets_.size();
922 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700923 // If we aren't compiling only reserve headers.
924 writer_->oat_class_headers_.reserve(num_classes);
925 if (writer->MayHaveCompiledMethods()) {
926 writer->oat_classes_.reserve(num_classes);
927 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100928 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100929 // If there are any classes, the class offsets allocation aligns the offset.
930 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100931 }
932
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100933 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100934 DexMethodVisitor::StartClass(dex_file, class_def_index);
935 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100936 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100937 return true;
938 }
939
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300940 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100941 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100942 // Fill in the compiled_methods_ array for methods that have a
943 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100944 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100945 // OatMethodOffsets for the compiled methods.
946 uint32_t method_idx = it.GetMemberIndex();
947 CompiledMethod* compiled_method =
948 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
949 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100950 if (HasCompiledCode(compiled_method)) {
951 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952 }
953 return true;
954 }
955
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100956 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100957 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko2c64a832018-01-04 11:31:56 +0000958 ClassStatus status;
Andreas Gampebb846102017-05-11 21:03:35 -0700959 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
960 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700961 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
962 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700963 // The oat class status is used only for verification of resolved classes,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000964 // so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
Andreas Gampebb846102017-05-11 21:03:35 -0700965 // during compile-time verification.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000966 status = ClassStatus::kErrorResolved;
Andreas Gampebb846102017-05-11 21:03:35 -0700967 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +0000968 status = ClassStatus::kNotReady;
Andreas Gampebb846102017-05-11 21:03:35 -0700969 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100970 }
971
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700972 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100973 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700974 compiled_methods_.size(),
975 status);
976 OatClassHeader& header = writer_->oat_class_headers_.back();
977 offset_ += header.SizeOf();
978 if (writer_->MayHaveCompiledMethods()) {
979 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100980 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700981 header.type_);
982 offset_ += writer_->oat_classes_.back().SizeOf();
983 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100984 return DexMethodVisitor::EndClass();
985 }
986
987 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000988 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100989 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100990};
991
Igor Murashkin545412b2017-08-17 15:26:54 -0700992// CompiledMethod + metadata required to do ordered method layout.
993//
994// See also OrderedMethodVisitor.
995struct OatWriter::OrderedMethodData {
996 ProfileCompilationInfo::MethodHotness method_hotness;
997 OatClass* oat_class;
998 CompiledMethod* compiled_method;
999 MethodReference method_reference;
1000 size_t method_offsets_index;
1001
1002 size_t class_def_index;
1003 uint32_t access_flags;
1004 const DexFile::CodeItem* code_item;
1005
1006 // A value of -1 denotes missing debug info
1007 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
1008 // Index into writer_->method_info_
1009 size_t debug_info_idx;
1010
1011 bool HasDebugInfo() const {
1012 return debug_info_idx != kDebugInfoIdxInvalid;
1013 }
1014
1015 // Bin each method according to the profile flags.
1016 //
1017 // Groups by e.g.
1018 // -- not hot at all
1019 // -- hot
1020 // -- hot and startup
1021 // -- hot and post-startup
1022 // -- hot and startup and poststartup
1023 // -- startup
1024 // -- startup and post-startup
1025 // -- post-startup
1026 //
1027 // (See MethodHotness enum definition for up-to-date binning order.)
1028 bool operator<(const OrderedMethodData& other) const {
1029 if (kOatWriterForceOatCodeLayout) {
1030 // Development flag: Override default behavior by sorting by name.
1031
1032 std::string name = method_reference.PrettyMethod();
1033 std::string other_name = other.method_reference.PrettyMethod();
1034 return name < other_name;
1035 }
1036
1037 // Use the profile's method hotness to determine sort order.
1038 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1039 return true;
1040 }
1041
1042 // Default: retain the original order.
1043 return false;
1044 }
1045
1046 private:
1047 // Used to determine relative order for OAT code layout when determining
1048 // binning.
1049 size_t GetMethodHotnessOrder() const {
1050 bool hotness[] = {
1051 method_hotness.IsHot(),
1052 method_hotness.IsStartup(),
1053 method_hotness.IsPostStartup()
1054 };
1055
1056
1057 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1058 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1059 // time that memory is referenced in the process.
1060
1061 size_t hotness_bits = 0;
1062 for (size_t i = 0; i < arraysize(hotness); ++i) {
1063 if (hotness[i]) {
1064 hotness_bits |= (1 << i);
1065 }
1066 }
1067
1068 if (kIsDebugBuild) {
1069 // Check for bins that are always-empty given a real profile.
1070 if (method_hotness.IsHot() &&
1071 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1072 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001073 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1074 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001075 // This is not fatal, so only warn.
1076 }
1077 }
1078
1079 return hotness_bits;
1080 }
1081};
1082
1083// Given a queue of CompiledMethod in some total order,
1084// visit each one in that order.
1085class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001086 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001087 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1088 : ordered_methods_(std::move(ordered_methods)) {
1089 }
1090
1091 virtual ~OrderedMethodVisitor() {}
1092
1093 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1094 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1095 if (!VisitStart()) {
1096 return false;
1097 }
1098
1099 for (const OrderedMethodData& method_data : ordered_methods_) {
1100 if (!VisitMethod(method_data)) {
1101 return false;
1102 }
1103 }
1104
1105 return VisitComplete();
1106 }
1107
1108 // Invoked once at the beginning, prior to visiting anything else.
1109 //
1110 // Return false to abort further visiting.
1111 virtual bool VisitStart() { return true; }
1112
1113 // Invoked repeatedly in the order specified by `ordered_methods`.
1114 //
1115 // Return false to short-circuit and to stop visiting further methods.
1116 virtual bool VisitMethod(const OrderedMethodData& method_data)
1117 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1118
1119 // Invoked once at the end, after every other method has been successfully visited.
1120 //
1121 // Return false to indicate the overall `Visit` has failed.
1122 virtual bool VisitComplete() = 0;
1123
1124 OrderedMethodList ReleaseOrderedMethods() {
1125 return std::move(ordered_methods_);
1126 }
1127
1128 private:
1129 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1130 // Methods can be inserted more than once in case of duplicated methods.
1131 OrderedMethodList ordered_methods_;
1132};
1133
1134// Visit every compiled method in order to determine its order within the OAT file.
1135// Methods from the same class do not need to be adjacent in the OAT code.
1136class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1137 public:
1138 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1139 : OatDexMethodVisitor(writer, offset) {
1140 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001141
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001142 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001143 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001144 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001145 }
1146
Igor Murashkin545412b2017-08-17 15:26:54 -07001147 bool VisitMethod(size_t class_def_method_index,
1148 const ClassDataItemIterator& it)
1149 OVERRIDE
1150 REQUIRES_SHARED(Locks::mutator_lock_) {
1151 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1152
Vladimir Marko49b0f452015-12-10 13:49:19 +00001153 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001154 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1155
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001156 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001157 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001158
Igor Murashkin545412b2017-08-17 15:26:54 -07001159 {
1160 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1161 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1162 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001163
Igor Murashkin545412b2017-08-17 15:26:54 -07001164 // Debug method info must be pushed in the original order
1165 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1166 // ElfCompilationUnitWriter::Write requires this.
1167 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1168 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1169 writer_->method_info_.push_back(info);
1170
1171 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1172 // once we know the offsets.
1173 //
1174 // Store the index into writer_->method_info_ since future push-backs
1175 // could reallocate and change the underlying data address.
1176 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001177 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001178 }
1179
1180 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1181
1182 // Lookup method hotness from profile, if available.
1183 // Otherwise assume a default of none-hotness.
1184 ProfileCompilationInfo::MethodHotness method_hotness =
1185 writer_->profile_compilation_info_ != nullptr
1186 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1187 : ProfileCompilationInfo::MethodHotness();
1188
1189 // Handle duplicate methods by pushing them repeatedly.
1190 OrderedMethodData method_data = {
1191 method_hotness,
1192 oat_class,
1193 compiled_method,
1194 method_ref,
1195 method_offsets_index_,
1196 class_def_index_,
1197 it.GetMethodAccessFlags(),
1198 it.GetMethodCodeItem(),
1199 debug_info_idx
1200 };
1201 ordered_methods_.push_back(method_data);
1202
1203 method_offsets_index_++;
1204 }
1205
1206 return true;
1207 }
1208
1209 OrderedMethodList ReleaseOrderedMethods() {
1210 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1211 // Sort by the method ordering criteria (in OrderedMethodData).
1212 // Since most methods will have the same ordering criteria,
1213 // we preserve the original insertion order within the same sort order.
1214 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1215 } else {
1216 // The profile-less behavior is as if every method had 0 hotness
1217 // associated with it.
1218 //
1219 // Since sorting all methods with hotness=0 should give back the same
1220 // order as before, don't do anything.
1221 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1222 }
1223
1224 return std::move(ordered_methods_);
1225 }
1226
1227 private:
1228 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1229 // Methods can be inserted more than once in case of duplicated methods.
1230 OrderedMethodList ordered_methods_;
1231};
1232
1233// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1234class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1235 public:
1236 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1237 size_t offset,
1238 OrderedMethodList ordered_methods)
1239 : LayoutReserveOffsetCodeMethodVisitor(writer,
1240 offset,
1241 writer->GetCompilerDriver()->GetCompilerOptions(),
1242 std::move(ordered_methods)) {
1243 }
1244
1245 virtual bool VisitComplete() OVERRIDE {
1246 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1247 if (generate_debug_info_) {
1248 std::vector<debug::MethodDebugInfo> thunk_infos =
1249 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1250 writer_->method_info_.insert(writer_->method_info_.end(),
1251 std::make_move_iterator(thunk_infos.begin()),
1252 std::make_move_iterator(thunk_infos.end()));
1253 }
1254 return true;
1255 }
1256
1257 virtual bool VisitMethod(const OrderedMethodData& method_data)
1258 OVERRIDE
1259 REQUIRES_SHARED(Locks::mutator_lock_) {
1260 OatClass* oat_class = method_data.oat_class;
1261 CompiledMethod* compiled_method = method_data.compiled_method;
1262 const MethodReference& method_ref = method_data.method_reference;
1263 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1264 size_t class_def_index = method_data.class_def_index;
1265 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001266 bool has_debug_info = method_data.HasDebugInfo();
1267 size_t debug_info_idx = method_data.debug_info_idx;
1268
1269 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1270
1271 // Derived from CompiledMethod.
1272 uint32_t quick_code_offset = 0;
1273
1274 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1275 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1276 uint32_t thumb_offset = compiled_method->CodeDelta();
1277
1278 // Deduplicate code arrays if we are not producing debuggable code.
1279 bool deduped = true;
1280 if (debuggable_) {
1281 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1282 if (quick_code_offset != 0u) {
1283 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1284 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001285 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001286 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1287 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001288 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001289 } else {
1290 quick_code_offset = dedupe_map_.GetOrCreate(
1291 compiled_method,
1292 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1293 deduped = false;
1294 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1295 });
1296 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297
Igor Murashkin545412b2017-08-17 15:26:54 -07001298 if (code_size != 0) {
1299 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1300 // TODO: Should this be a hard failure?
1301 LOG(WARNING) << "Multiple definitions of "
1302 << method_ref.dex_file->PrettyMethod(method_ref.index)
1303 << " offsets " << relative_patcher_->GetOffset(method_ref)
1304 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001305 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001306 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1307 }
1308 }
1309
1310 // Update quick method header.
1311 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1312 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1313 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1314 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1315 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1316 // to 0-offset and we need to adjust it by code_offset.
1317 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001318 CHECK(!compiled_method->GetQuickCode().empty());
1319 // If the code is compiled, we write the offset of the stack map relative
1320 // to the code.
1321 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001322 vmap_table_offset += code_offset;
1323 DCHECK_LT(vmap_table_offset, code_offset);
1324 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001325 if (method_info_offset != 0u) {
1326 method_info_offset += code_offset;
1327 DCHECK_LT(method_info_offset, code_offset);
1328 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001329 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1330 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1331 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1332 *method_header = OatQuickMethodHeader(vmap_table_offset,
1333 method_info_offset,
1334 frame_size_in_bytes,
1335 core_spill_mask,
1336 fp_spill_mask,
1337 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001338
Igor Murashkin545412b2017-08-17 15:26:54 -07001339 if (!deduped) {
1340 // Update offsets. (Checksum is updated when writing.)
1341 offset_ += sizeof(*method_header); // Method header is prepended before code.
1342 offset_ += code_size;
1343 // Record absolute patch locations.
1344 if (!compiled_method->GetPatches().empty()) {
1345 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1346 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1347 if (!patch.IsPcRelative()) {
1348 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001349 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001350 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001351 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001352 }
1353
Igor Murashkin545412b2017-08-17 15:26:54 -07001354 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1355 if (generate_debug_info_ && code_size != 0) {
1356 DCHECK(has_debug_info);
1357
1358 bool has_code_info = method_header->IsOptimized();
1359 // Record debug information for this function if we are doing that.
1360 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
David Srbeckyc684f332018-01-19 17:38:06 +00001361 DCHECK(info.custom_name.empty());
Igor Murashkin545412b2017-08-17 15:26:54 -07001362 info.dex_file = method_ref.dex_file;
1363 info.class_def_index = class_def_index;
1364 info.dex_method_index = method_ref.index;
1365 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001366 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1367 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001368 info.isa = compiled_method->GetInstructionSet();
1369 info.deduped = deduped;
1370 info.is_native_debuggable = native_debuggable_;
1371 info.is_optimized = method_header->IsOptimized();
1372 info.is_code_address_text_relative = true;
1373 info.code_address = code_offset - executable_offset_;
1374 info.code_size = code_size;
1375 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1376 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1377 info.cfi = compiled_method->GetCFIInfo();
1378 } else {
1379 DCHECK(!has_debug_info);
1380 }
1381
1382 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1383 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1384 offsets->code_offset_ = quick_code_offset;
1385
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001386 return true;
1387 }
1388
Igor Murashkin545412b2017-08-17 15:26:54 -07001389 size_t GetOffset() const {
1390 return offset_;
1391 }
1392
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001393 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001394 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1395 size_t offset,
1396 const CompilerOptions& compiler_options,
1397 OrderedMethodList ordered_methods)
1398 : OrderedMethodVisitor(std::move(ordered_methods)),
1399 writer_(writer),
1400 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001401 relative_patcher_(writer->relative_patcher_),
1402 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1403 debuggable_(compiler_options.GetDebuggable()),
1404 native_debuggable_(compiler_options.GetNativeDebuggable()),
1405 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1406 writer->absolute_patch_locations_.reserve(
1407 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1408 }
1409
Vladimir Marko20f85592015-03-19 10:07:02 +00001410 struct CodeOffsetsKeyComparator {
1411 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001412 // Code is deduplicated by CompilerDriver, compare only data pointers.
1413 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1414 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001415 }
1416 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001417 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1418 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001419 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001420 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1421 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1422 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001423 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1424 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001425 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001426 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1427 return rhs->IsIntrinsic();
1428 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001429 return false;
1430 }
1431 };
1432
David Srbecky009e2a62015-04-15 02:46:30 +01001433 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001434 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001435 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001436 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001437 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1438 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001439 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1440 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1441 }
1442
Igor Murashkin545412b2017-08-17 15:26:54 -07001443 OatWriter* writer_;
1444
1445 // Offset of the code of the compiled methods.
1446 size_t offset_;
1447
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001448 // Deduplication is already done on a pointer basis by the compiler driver,
1449 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001450 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001451
Vladimir Marko1b404a82017-09-01 13:35:26 +01001452 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001453 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001454 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001455 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001456 const bool native_debuggable_;
1457 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001458};
1459
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001460class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1461 public:
1462 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001463 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001464
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001465 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001466 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001467 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1469
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001470 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001471 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001472 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001473
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001474 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1475 uint32_t map_size = map.size() * sizeof(map[0]);
1476 if (map_size != 0u) {
1477 size_t offset = dedupe_map_.GetOrCreate(
1478 map.data(),
1479 [this, map_size]() {
1480 uint32_t new_offset = offset_;
1481 offset_ += map_size;
1482 return new_offset;
1483 });
1484 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1485 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1486 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001487 }
1488 ++method_offsets_index_;
1489 }
1490
1491 return true;
1492 }
1493
1494 private:
1495 // Deduplication is already done on a pointer basis by the compiler driver,
1496 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001497 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001498};
1499
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001500class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1501 public:
1502 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1503
1504 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001505 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001506 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1507 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1508
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001509 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001510 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1511 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1512 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1513 const uint32_t map_size = map.size() * sizeof(map[0]);
1514 if (map_size != 0u) {
1515 size_t offset = dedupe_map_.GetOrCreate(
1516 map.data(),
1517 [this, map_size]() {
1518 uint32_t new_offset = offset_;
1519 offset_ += map_size;
1520 return new_offset;
1521 });
1522 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1523 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1524 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1525 }
1526 ++method_offsets_index_;
1527 }
1528
1529 return true;
1530 }
1531
1532 private:
1533 // Deduplication is already done on a pointer basis by the compiler driver,
1534 // so we can simply compare the pointers to find out if things are duplicated.
1535 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1536};
1537
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001538class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1539 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001540 InitImageMethodVisitor(OatWriter* writer,
1541 size_t offset,
1542 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001543 : OatDexMethodVisitor(writer, offset),
1544 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001545 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001546 dex_files_(dex_files),
1547 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001548
1549 // Handle copied methods here. Copy pointer to quick code from
1550 // an origin method to a copied method only if they are
1551 // in the same oat file. If the origin and the copied methods are
1552 // in different oat files don't touch the copied method.
1553 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001554 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001555 REQUIRES_SHARED(Locks::mutator_lock_) {
1556 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1557 // Skip classes that are not in the image.
1558 if (!IsImageClass()) {
1559 return true;
1560 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001561 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001562 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1563 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1564 if (klass != nullptr) {
1565 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1566 // Find origin method. Declaring class and dex_method_idx
1567 // in the copied method should be the same as in the origin
1568 // method.
1569 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001570 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001571 declaring_class->GetDexCache(),
1572 method.GetDexMethodIndex(),
1573 pointer_size_);
1574 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001575 CHECK(!origin->IsDirect());
1576 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001577 if (IsInOatFile(&declaring_class->GetDexFile())) {
1578 const void* code_ptr =
1579 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1580 if (code_ptr == nullptr) {
1581 methods_to_process_.push_back(std::make_pair(&method, origin));
1582 } else {
1583 method.SetEntryPointFromQuickCompiledCodePtrSize(
1584 code_ptr, pointer_size_);
1585 }
1586 }
1587 }
1588 }
1589 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001590 }
1591
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001592 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001593 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001594 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001595 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001596 return true;
1597 }
1598
Vladimir Marko49b0f452015-12-10 13:49:19 +00001599 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001600 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1601
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001602 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001603 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001604 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1605 offsets = oat_class->method_offsets_[method_offsets_index_];
1606 ++method_offsets_index_;
1607 }
1608
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001609 Thread* self = Thread::Current();
1610 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001611 ArtMethod* method;
1612 if (writer_->HasBootImage()) {
1613 const InvokeType invoke_type = it.GetMethodInvokeType(
1614 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001615 // Unchecked as we hold mutator_lock_ on entry.
1616 ScopedObjectAccessUnchecked soa(self);
1617 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001618 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001619 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001620 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001621 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Marko89011192017-12-11 13:45:05 +00001622 /* referrer */ nullptr,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001623 invoke_type);
1624 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001625 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001626 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001627 self->AssertPendingException();
1628 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001629 std::string dump = exc->Dump();
1630 LOG(FATAL) << dump;
1631 UNREACHABLE();
1632 }
1633 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001634 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001635 // 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 +01001636 // entrypoint. This is not fatal since we shall use a resolution method.
1637 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001638 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001639 if (method != nullptr &&
1640 compiled_method != nullptr &&
1641 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001642 method->SetEntryPointFromQuickCompiledCodePtrSize(
1643 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1644 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001645
1646 return true;
1647 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001648
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001649 // Check whether current class is image class
1650 bool IsImageClass() {
1651 const DexFile::TypeId& type_id =
1652 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1653 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1654 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1655 }
1656
1657 // Check whether specified dex file is in the compiled oat file.
1658 bool IsInOatFile(const DexFile* dex_file) {
1659 return ContainsElement(*dex_files_, dex_file);
1660 }
1661
1662 // Assign a pointer to quick code for copied methods
1663 // not handled in the method StartClass
1664 void Postprocess() {
1665 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1666 ArtMethod* method = p.first;
1667 ArtMethod* origin = p.second;
1668 const void* code_ptr =
1669 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1670 if (code_ptr != nullptr) {
1671 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1672 }
1673 }
1674 }
1675
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001676 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001677 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001678 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001679 const std::vector<const DexFile*>* dex_files_;
1680 ClassLinker* const class_linker_;
1681 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001682};
1683
Igor Murashkin545412b2017-08-17 15:26:54 -07001684class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001685 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001686 WriteCodeMethodVisitor(OatWriter* writer,
1687 OutputStream* out,
1688 const size_t file_offset,
1689 size_t relative_offset,
1690 OrderedMethodList ordered_methods)
1691 : OrderedMethodVisitor(std::move(ordered_methods)),
1692 writer_(writer),
1693 offset_(relative_offset),
1694 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001695 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1696 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1697 out_(out),
1698 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001699 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001700 dex_cache_(nullptr),
1701 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001702 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001703 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001704 // If we're creating the image, the address space must be ready so that we can apply patches.
1705 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001706 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001707 }
1708
Igor Murashkin545412b2017-08-17 15:26:54 -07001709 virtual bool VisitStart() OVERRIDE {
1710 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001711 }
1712
Igor Murashkin545412b2017-08-17 15:26:54 -07001713 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001714 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001715 dex_file_ = dex_file;
1716
1717 // Ordered method visiting is only for compiled methods.
1718 DCHECK(writer_->MayHaveCompiledMethods());
1719
Mathieu Chartier72041a02017-07-14 18:23:25 -07001720 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1721 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1722 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1723 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1724 DCHECK(dex_cache_ != nullptr);
1725 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001726 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001727 }
1728
1729 virtual bool VisitComplete() {
1730 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1731 if (UNLIKELY(offset_ == 0u)) {
1732 PLOG(ERROR) << "Failed to write final relative call thunks";
1733 return false;
1734 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001735 return true;
1736 }
1737
Igor Murashkin545412b2017-08-17 15:26:54 -07001738 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001739 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001740 const MethodReference& method_ref = method_data.method_reference;
1741 UpdateDexFileAndDexCache(method_ref.dex_file);
1742
1743 OatClass* oat_class = method_data.oat_class;
1744 CompiledMethod* compiled_method = method_data.compiled_method;
1745 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001746
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001747 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001748 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001749 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001750
Igor Murashkin545412b2017-08-17 15:26:54 -07001751 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1752 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1753 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001754
Igor Murashkin545412b2017-08-17 15:26:54 -07001755 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1756 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1757
1758 // Deduplicate code arrays.
1759 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1760 if (method_offsets.code_offset_ > offset_) {
1761 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1762 if (offset_ == 0u) {
1763 ReportWriteFailure("relative call thunk", method_ref);
1764 return false;
1765 }
1766 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1767 if (alignment_size != 0) {
1768 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1769 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001770 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001771 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001772 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001773 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001774 }
1775 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1776 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1777 DCHECK_EQ(method_offsets.code_offset_,
1778 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1779 << dex_file_->PrettyMethod(method_ref.index);
1780 const OatQuickMethodHeader& method_header =
1781 oat_class->method_headers_[method_offsets_index];
1782 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1783 ReportWriteFailure("method header", method_ref);
1784 return false;
1785 }
1786 writer_->size_method_header_ += sizeof(method_header);
1787 offset_ += sizeof(method_header);
1788 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001789
Igor Murashkin545412b2017-08-17 15:26:54 -07001790 if (!compiled_method->GetPatches().empty()) {
1791 patched_code_.assign(quick_code.begin(), quick_code.end());
1792 quick_code = ArrayRef<const uint8_t>(patched_code_);
1793 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1794 uint32_t literal_offset = patch.LiteralOffset();
1795 switch (patch.GetType()) {
Vladimir Markob066d432018-01-03 13:14:37 +00001796 case LinkerPatch::Type::kDataBimgRelRo: {
1797 uint32_t target_offset =
1798 writer_->data_bimg_rel_ro_start_ +
1799 writer_->data_bimg_rel_ro_entries_.Get(patch.BootImageOffset());
1800 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1801 patch,
1802 offset_ + literal_offset,
1803 target_offset);
1804 break;
1805 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001806 case LinkerPatch::Type::kMethodBssEntry: {
1807 uint32_t target_offset =
1808 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1809 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1810 patch,
1811 offset_ + literal_offset,
1812 target_offset);
1813 break;
1814 }
1815 case LinkerPatch::Type::kCallRelative: {
1816 // NOTE: Relative calls across oat files are not supported.
1817 uint32_t target_offset = GetTargetOffset(patch);
1818 writer_->relative_patcher_->PatchCall(&patched_code_,
1819 literal_offset,
1820 offset_ + literal_offset,
1821 target_offset);
1822 break;
1823 }
1824 case LinkerPatch::Type::kStringRelative: {
1825 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1826 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1827 patch,
1828 offset_ + literal_offset,
1829 target_offset);
1830 break;
1831 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001832 case LinkerPatch::Type::kStringBssEntry: {
1833 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1834 uint32_t target_offset =
1835 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1836 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1837 patch,
1838 offset_ + literal_offset,
1839 target_offset);
1840 break;
1841 }
1842 case LinkerPatch::Type::kTypeRelative: {
1843 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1844 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1845 patch,
1846 offset_ + literal_offset,
1847 target_offset);
1848 break;
1849 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001850 case LinkerPatch::Type::kTypeBssEntry: {
1851 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1852 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1853 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1854 patch,
1855 offset_ + literal_offset,
1856 target_offset);
1857 break;
1858 }
1859 case LinkerPatch::Type::kCall: {
1860 uint32_t target_offset = GetTargetOffset(patch);
1861 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1862 break;
1863 }
1864 case LinkerPatch::Type::kMethodRelative: {
1865 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1866 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1867 patch,
1868 offset_ + literal_offset,
1869 target_offset);
1870 break;
1871 }
1872 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1873 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1874 patch,
1875 offset_ + literal_offset);
1876 break;
1877 }
1878 default: {
1879 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1880 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001881 }
1882 }
1883 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001884 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001885
1886 if (!out->WriteFully(quick_code.data(), code_size)) {
1887 ReportWriteFailure("method code", method_ref);
1888 return false;
1889 }
1890 writer_->size_code_ += code_size;
1891 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001892 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001893 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001894
1895 return true;
1896 }
1897
Igor Murashkin545412b2017-08-17 15:26:54 -07001898 size_t GetOffset() const {
1899 return offset_;
1900 }
1901
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001902 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001903 OatWriter* const writer_;
1904
1905 // Updated in VisitMethod as methods are written out.
1906 size_t offset_;
1907
1908 // Potentially varies with every different VisitMethod.
1909 // Used to determine which DexCache to use when finding ArtMethods.
1910 const DexFile* dex_file_;
1911
1912 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001913 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001914 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001915 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001916 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001917 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001918 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001919 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001920 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001921 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001922 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001923
Igor Murashkin545412b2017-08-17 15:26:54 -07001924 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001925 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001926 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001927 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001928
Mathieu Chartiere401d142015-04-22 13:56:20 -07001929 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001930 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001931 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001932 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001933 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1934 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001935 ArtMethod* method =
1936 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001937 CHECK(method != nullptr);
1938 return method;
1939 }
1940
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001941 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001942 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1943 // If there's no new compiled code, either we're compiling an app and the target method
1944 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001945 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001946 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001947 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001948 const void* oat_code_offset =
1949 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001950 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001951 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001952 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1953 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1954 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1955 target_offset = PointerToLowMemUInt32(oat_code_offset);
1956 } else {
1957 target_offset = target->IsNative()
1958 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1959 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1960 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001961 }
1962 return target_offset;
1963 }
1964
Vladimir Markocd556b02017-02-03 11:47:34 +00001965 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001966 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001967 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001968 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001969 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1970 }
1971
Vladimir Marko28e012a2017-12-07 11:22:59 +00001972 ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1973 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001974 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001975 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001976 ObjPtr<mirror::Class> type =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001977 class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001978 CHECK(type != nullptr);
Vladimir Marko28e012a2017-12-07 11:22:59 +00001979 return type;
Vladimir Markof4da6752014-08-01 19:04:18 +01001980 }
1981
Vladimir Marko28e012a2017-12-07 11:22:59 +00001982 ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1983 REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001984 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Markoa64b52d2017-12-08 16:27:49 +00001985 ObjPtr<mirror::String> string =
1986 linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001987 DCHECK(string != nullptr);
1988 DCHECK(writer_->HasBootImage() ||
1989 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1990 return string;
1991 }
1992
Vladimir Marko65979462017-05-19 17:25:12 +01001993 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1994 DCHECK(writer_->HasBootImage());
1995 method = writer_->image_writer_->GetImageMethodAddress(method);
1996 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1997 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1998 // TODO: Clean up offset types. The target offset must be treated as signed.
1999 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
2000 }
2001
Vladimir Marko28e012a2017-12-07 11:22:59 +00002002 uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
2003 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002004 DCHECK(writer_->HasBootImage());
Vladimir Marko28e012a2017-12-07 11:22:59 +00002005 object = writer_->image_writer_->GetImageAddress(object.Ptr());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002006 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
2007 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
2008 // TODO: Clean up offset types. The target offset must be treated as signed.
Vladimir Marko28e012a2017-12-07 11:22:59 +00002009 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002010 }
2011
Vladimir Markof4da6752014-08-01 19:04:18 +01002012 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002013 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002014 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002015 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01002016 } else {
2017 // NOTE: We're using linker patches for app->boot references when the image can
2018 // be relocated and therefore we need to emit .oat_patches. We're not using this
2019 // for app->app references, so check that the object is in the image space.
2020 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01002021 }
Vladimir Marko09d09432015-09-08 13:47:48 +01002022 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01002023 uint32_t address = PointerToLowMemUInt32(object);
2024 DCHECK_LE(offset + 4, code->size());
2025 uint8_t* data = &(*code)[offset];
2026 data[0] = address & 0xffu;
2027 data[1] = (address >> 8) & 0xffu;
2028 data[2] = (address >> 16) & 0xffu;
2029 data[3] = (address >> 24) & 0xffu;
2030 }
2031
2032 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002033 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01002034 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002035 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002036 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
2037 // TODO: Clean up offset types.
2038 // The target_offset must be treated as signed for cross-oat patching.
2039 const void* target = reinterpret_cast<const void*>(
2040 writer_->image_writer_->GetOatDataBegin(oat_index) +
2041 static_cast<int32_t>(target_offset));
2042 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01002043 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002044 DCHECK_LE(offset + 4, code->size());
2045 uint8_t* data = &(*code)[offset];
2046 data[0] = address & 0xffu;
2047 data[1] = (address >> 8) & 0xffu;
2048 data[2] = (address >> 16) & 0xffu;
2049 data[3] = (address >> 24) & 0xffu;
2050 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002051};
2052
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002053class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2054 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002055 WriteMapMethodVisitor(OatWriter* writer,
2056 OutputStream* out,
2057 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002058 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002059 : OatDexMethodVisitor(writer, relative_offset),
2060 out_(out),
2061 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002062
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002063 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002064 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002065 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2066
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002067 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002068 size_t file_offset = file_offset_;
2069 OutputStream* out = out_;
2070
Mingyao Yang063fc772016-08-02 11:02:54 -07002071 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002072 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002073 ++method_offsets_index_;
2074
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002075 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2076 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2077 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002078 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002079
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002080 // If vdex is enabled, only emit the map for compiled code. The quickening info
2081 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002082 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002083 // Transform map_offset to actual oat data offset.
2084 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2085 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002086 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002087
2088 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2089 size_t map_size = map.size() * sizeof(map[0]);
2090 if (map_offset == offset_) {
2091 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002092 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002093 ReportWriteFailure(it);
2094 return false;
2095 }
2096 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002097 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002098 }
2099 DCHECK_OFFSET_();
2100 }
2101
2102 return true;
2103 }
2104
2105 private:
2106 OutputStream* const out_;
2107 size_t const file_offset_;
2108
2109 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002110 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002111 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002112 }
2113};
2114
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002115class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2116 public:
2117 WriteMethodInfoVisitor(OatWriter* writer,
2118 OutputStream* out,
2119 const size_t file_offset,
2120 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002121 : OatDexMethodVisitor(writer, relative_offset),
2122 out_(out),
2123 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002124
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002125 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002126 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2127 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2128
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002129 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002130 size_t file_offset = file_offset_;
2131 OutputStream* out = out_;
2132 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2133 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2134 ++method_offsets_index_;
2135 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2136 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2137 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2138 << dex_file_->PrettyMethod(it.GetMemberIndex());
2139 if (map_offset != 0u) {
2140 // Transform map_offset to actual oat data offset.
2141 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2142 DCHECK_NE(map_offset, 0u);
2143 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2144
2145 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2146 size_t map_size = map.size() * sizeof(map[0]);
2147 if (map_offset == offset_) {
2148 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2149 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2150 ReportWriteFailure(it);
2151 return false;
2152 }
2153 offset_ += map_size;
2154 }
2155 }
2156 DCHECK_OFFSET_();
2157 }
2158
2159 return true;
2160 }
2161
2162 private:
2163 OutputStream* const out_;
2164 size_t const file_offset_;
2165
2166 void ReportWriteFailure(const ClassDataItemIterator& it) {
2167 PLOG(ERROR) << "Failed to write map for "
2168 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2169 }
2170};
2171
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002172// Visit all methods from all classes in all dex files with the specified visitor.
2173bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2174 for (const DexFile* dex_file : *dex_files_) {
2175 const size_t class_def_count = dex_file->NumClassDefs();
2176 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2177 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2178 return false;
2179 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002180 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002181 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2182 const uint8_t* class_data = dex_file->GetClassData(class_def);
2183 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2184 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002185 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002186 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002187 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002188 if (!visitor->VisitMethod(class_def_method_index, it)) {
2189 return false;
2190 }
2191 ++class_def_method_index;
2192 it.Next();
2193 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002194 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002195 }
2196 }
2197 if (UNLIKELY(!visitor->EndClass())) {
2198 return false;
2199 }
2200 }
2201 }
2202 return true;
2203}
2204
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002205size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2206 const InstructionSetFeatures* instruction_set_features,
2207 uint32_t num_dex_files,
2208 SafeMap<std::string, std::string>* key_value_store) {
2209 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2210 oat_header_.reset(OatHeader::Create(instruction_set,
2211 instruction_set_features,
2212 num_dex_files,
2213 key_value_store));
2214 size_oat_header_ += sizeof(OatHeader);
2215 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002216 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002217}
2218
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002219size_t OatWriter::InitClassOffsets(size_t offset) {
2220 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002221 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002222 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2223 if (!oat_dex_file.class_offsets_.empty()) {
2224 // Class offsets are required to be 4 byte aligned.
2225 offset = RoundUp(offset, 4u);
2226 oat_dex_file.class_offsets_offset_ = offset;
2227 offset += oat_dex_file.GetClassOffsetsRawSize();
2228 DCHECK_ALIGNED(offset, 4u);
2229 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002230 }
2231 return offset;
2232}
2233
Brian Carlstrom389efb02012-01-11 12:06:26 -08002234size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002235 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002236 InitOatClassesMethodVisitor visitor(this, offset);
2237 bool success = VisitDexMethods(&visitor);
2238 CHECK(success);
2239 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002240
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002241 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002242 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002243 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2244 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002245 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002246 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002247 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002248 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002249 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002250 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002251
2252 return offset;
2253}
2254
2255size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002256 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002257 return offset;
2258 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002259 {
2260 InitMapMethodVisitor visitor(this, offset);
2261 bool success = VisitDexMethods(&visitor);
2262 DCHECK(success);
2263 offset = visitor.GetOffset();
2264 }
2265 {
2266 InitMethodInfoVisitor visitor(this, offset);
2267 bool success = VisitDexMethods(&visitor);
2268 DCHECK(success);
2269 offset = visitor.GetOffset();
2270 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002271 return offset;
2272}
2273
Vladimir Markof3c52b42017-11-17 17:32:12 +00002274template <typename GetBssOffset>
2275static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2276 size_t slot_size,
2277 const BitVector& indexes,
2278 GetBssOffset get_bss_offset) {
2279 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2280 size_t number_of_entries = 0u;
2281 bool first_index = true;
2282 for (uint32_t index : indexes.Indexes()) {
2283 uint32_t bss_offset = get_bss_offset(index);
2284 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2285 encoder.Reset(index, bss_offset);
2286 ++number_of_entries;
2287 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002288 }
2289 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002290 DCHECK_NE(number_of_entries, 0u);
2291 return number_of_entries;
2292}
2293
2294template <typename GetBssOffset>
2295static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2296 size_t slot_size,
2297 const BitVector& indexes,
2298 GetBssOffset get_bss_offset) {
2299 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2300 slot_size,
2301 indexes,
2302 get_bss_offset);
2303 return IndexBssMapping::ComputeSize(number_of_entries);
2304}
2305
2306size_t OatWriter::InitIndexBssMappings(size_t offset) {
2307 if (bss_method_entry_references_.empty() &&
2308 bss_type_entry_references_.empty() &&
2309 bss_string_entry_references_.empty()) {
2310 return offset;
2311 }
2312 // If there are any classes, the class offsets allocation aligns the offset
2313 // and we cannot have any index bss mappings without class offsets.
2314 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2315 DCHECK_ALIGNED(offset, 4u);
2316
2317 size_t number_of_method_dex_files = 0u;
2318 size_t number_of_type_dex_files = 0u;
2319 size_t number_of_string_dex_files = 0u;
2320 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2321 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2322 const DexFile* dex_file = (*dex_files_)[i];
2323 auto method_it = bss_method_entry_references_.find(dex_file);
2324 if (method_it != bss_method_entry_references_.end()) {
2325 const BitVector& method_indexes = method_it->second;
2326 ++number_of_method_dex_files;
2327 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2328 offset += CalculateIndexBssMappingSize(
2329 dex_file->NumMethodIds(),
2330 static_cast<size_t>(pointer_size),
2331 method_indexes,
2332 [=](uint32_t index) {
2333 return bss_method_entries_.Get({dex_file, index});
2334 });
2335 }
2336
2337 auto type_it = bss_type_entry_references_.find(dex_file);
2338 if (type_it != bss_type_entry_references_.end()) {
2339 const BitVector& type_indexes = type_it->second;
2340 ++number_of_type_dex_files;
2341 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2342 offset += CalculateIndexBssMappingSize(
2343 dex_file->NumTypeIds(),
2344 sizeof(GcRoot<mirror::Class>),
2345 type_indexes,
2346 [=](uint32_t index) {
2347 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2348 });
2349 }
2350
2351 auto string_it = bss_string_entry_references_.find(dex_file);
2352 if (string_it != bss_string_entry_references_.end()) {
2353 const BitVector& string_indexes = string_it->second;
2354 ++number_of_string_dex_files;
2355 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2356 offset += CalculateIndexBssMappingSize(
2357 dex_file->NumStringIds(),
2358 sizeof(GcRoot<mirror::String>),
2359 string_indexes,
2360 [=](uint32_t index) {
2361 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2362 });
2363 }
2364 }
2365 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2366 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2367 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2368 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002369 return offset;
2370}
2371
2372size_t OatWriter::InitOatDexFiles(size_t offset) {
2373 // Initialize offsets of oat dex files.
2374 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2375 oat_dex_file.offset_ = offset;
2376 offset += oat_dex_file.SizeOf();
2377 }
2378 return offset;
2379}
2380
Brian Carlstrome24fa612011-09-29 00:53:55 -07002381size_t OatWriter::InitOatCode(size_t offset) {
2382 // calculate the offsets within OatHeader to executable code
2383 size_t old_offset = offset;
2384 // required to be on a new page boundary
2385 offset = RoundUp(offset, kPageSize);
2386 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002387 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002388 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2389 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2390 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002391 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002392 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002393 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2394 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002395
Vladimir Marko1b404a82017-09-01 13:35:26 +01002396 #define DO_TRAMPOLINE(field, fn_name) \
2397 offset = CompiledCode::AlignCode(offset, instruction_set); \
2398 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2399 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2400 (field) = compiler_driver_->Create ## fn_name(); \
2401 if (generate_debug_info) { \
2402 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +00002403 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +01002404 info.isa = instruction_set; \
2405 info.is_code_address_text_relative = true; \
2406 /* Use the code offset rather than the `adjusted_offset`. */ \
2407 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2408 info.code_size = (field)->size(); \
2409 method_info_.push_back(std::move(info)); \
2410 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002411 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002412
Ian Rogers848871b2013-08-05 10:56:33 -07002413 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002414 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002415 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002416 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2417 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002418
Ian Rogers848871b2013-08-05 10:56:33 -07002419 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002420 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002421 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002422 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002423 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002424 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002425 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002426 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002427 return offset;
2428}
2429
2430size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002431 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002432 if (kOatWriterDebugOatCodeLayout) {
2433 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2434 << this << "), "
2435 << "compilation is disabled";
2436 }
2437
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002438 return offset;
2439 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002440 bool success = false;
2441
2442 {
2443 ScopedObjectAccess soa(Thread::Current());
2444
2445 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2446 success = VisitDexMethods(&layout_code_visitor);
2447 DCHECK(success);
2448
2449 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2450 this,
2451 offset,
2452 layout_code_visitor.ReleaseOrderedMethods());
2453 success = layout_reserve_code_visitor.Visit();
2454 DCHECK(success);
2455 offset = layout_reserve_code_visitor.GetOffset();
2456
2457 // Save the method order because the WriteCodeMethodVisitor will need this
2458 // order again.
2459 DCHECK(ordered_methods_ == nullptr);
2460 ordered_methods_.reset(
2461 new OrderedMethodList(
2462 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2463
2464 if (kOatWriterDebugOatCodeLayout) {
2465 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2466 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2467 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2468 LOG(INFO) << pretty_name
2469 << "@ offset "
2470 << relative_patcher_->GetOffset(ordered_method.method_reference)
2471 << " X hotness "
2472 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2473 }
2474 }
2475 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002476
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002477 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002478 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002479 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002480 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002481 DCHECK(success);
2482 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002483 }
Logan Chien8b977d32012-02-21 19:14:55 +08002484
Brian Carlstrome24fa612011-09-29 00:53:55 -07002485 return offset;
2486}
2487
Vladimir Markob066d432018-01-03 13:14:37 +00002488size_t OatWriter::InitDataBimgRelRoLayout(size_t offset) {
2489 DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
2490 if (data_bimg_rel_ro_entries_.empty()) {
2491 // Nothing to put to the .data.bimg.rel.ro section.
2492 return offset;
2493 }
2494
2495 data_bimg_rel_ro_start_ = RoundUp(offset, kPageSize);
2496
2497 for (auto& entry : data_bimg_rel_ro_entries_) {
2498 size_t& entry_offset = entry.second;
2499 entry_offset = data_bimg_rel_ro_size_;
2500 data_bimg_rel_ro_size_ += sizeof(uint32_t);
2501 }
2502
2503 offset = data_bimg_rel_ro_start_ + data_bimg_rel_ro_size_;
2504 return offset;
2505}
2506
Vladimir Markoaad75c62016-10-03 08:46:48 +00002507void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002508 {
2509 InitBssLayoutMethodVisitor visitor(this);
2510 bool success = VisitDexMethods(&visitor);
2511 DCHECK(success);
2512 }
2513
2514 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002515 if (HasBootImage()) {
2516 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002517 }
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002518 if (bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002519 bss_type_entries_.empty() &&
2520 bss_string_entries_.empty()) {
2521 // Nothing to put to the .bss section.
2522 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002523 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002524
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002525 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002526 bss_methods_offset_ = bss_size_;
2527
2528 // Prepare offsets for .bss ArtMethod entries.
2529 for (auto& entry : bss_method_entries_) {
2530 DCHECK_EQ(entry.second, 0u);
2531 entry.second = bss_size_;
2532 bss_size_ += static_cast<size_t>(pointer_size);
2533 }
2534
Vladimir Markoaad75c62016-10-03 08:46:48 +00002535 bss_roots_offset_ = bss_size_;
2536
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002537 // Prepare offsets for .bss Class entries.
2538 for (auto& entry : bss_type_entries_) {
2539 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002540 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002541 bss_size_ += sizeof(GcRoot<mirror::Class>);
2542 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002543 // Prepare offsets for .bss String entries.
2544 for (auto& entry : bss_string_entries_) {
2545 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002546 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002547 bss_size_ += sizeof(GcRoot<mirror::String>);
2548 }
2549}
2550
David Srbeckybc90fd02015-04-22 19:40:27 +01002551bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002552 CHECK(write_state_ == WriteState::kWriteRoData);
2553
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002554 size_t file_offset = oat_data_offset_;
2555 off_t current_offset = out->Seek(0, kSeekCurrent);
2556 if (current_offset == static_cast<off_t>(-1)) {
2557 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2558 }
2559 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2560 size_t relative_offset = current_offset - file_offset;
2561
Vladimir Markoe079e212016-05-25 12:49:49 +01002562 // Wrap out to update checksum with each write.
2563 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2564 out = &checksum_updating_out;
2565
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002566 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2567 if (relative_offset == 0) {
2568 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002569 return false;
2570 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002571
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002572 relative_offset = WriteClasses(out, file_offset, relative_offset);
2573 if (relative_offset == 0) {
2574 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002575 return false;
2576 }
2577
Vladimir Markof3c52b42017-11-17 17:32:12 +00002578 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002579 if (relative_offset == 0) {
2580 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002581 return false;
2582 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002583
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002584 relative_offset = WriteMaps(out, file_offset, relative_offset);
2585 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002586 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2587 return false;
2588 }
2589
2590 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2591 if (relative_offset == 0) {
2592 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002593 return false;
2594 }
2595
David Srbeckybc90fd02015-04-22 19:40:27 +01002596 // Write padding.
2597 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2598 relative_offset += size_executable_offset_alignment_;
2599 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2600 size_t expected_file_offset = file_offset + relative_offset;
2601 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2602 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2603 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2604 return 0;
2605 }
2606 DCHECK_OFFSET();
2607
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002608 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002609 return true;
2610}
2611
Mathieu Chartier210531f2018-01-12 10:15:51 -08002612class OatWriter::WriteQuickeningInfoMethodVisitor {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002613 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002614 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out)
2615 : writer_(writer),
2616 out_(out) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002617
Mathieu Chartier210531f2018-01-12 10:15:51 -08002618 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002619 // Map of offsets for quicken info related to method indices.
2620 SafeMap<const uint8_t*, uint32_t> offset_map;
2621 // Use method index order to minimize the encoded size of the offset table.
Mathieu Chartier210531f2018-01-12 10:15:51 -08002622 for (const DexFile* dex_file : dex_files) {
2623 std::vector<uint32_t>* const offsets =
2624 &quicken_info_offset_indices_.Put(dex_file, std::vector<uint32_t>())->second;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002625 for (uint32_t method_idx = 0; method_idx < dex_file->NumMethodIds(); ++method_idx) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002626 uint32_t offset = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002627 MethodReference method_ref(dex_file, method_idx);
2628 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(method_ref);
2629 if (compiled_method != nullptr && HasQuickeningInfo(compiled_method)) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002630 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Mathieu Chartier210531f2018-01-12 10:15:51 -08002631
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002632 // Record each index if required. written_bytes_ is the offset from the start of the
2633 // quicken info data.
2634 // May be already inserted for deduplicate items.
2635 // Add offset of one to make sure 0 represents unused.
2636 auto pair = offset_map.emplace(map.data(), written_bytes_ + 1);
2637 offset = pair.first->second;
2638 // Write out the map if it's not already written.
2639 if (pair.second) {
2640 const uint32_t length = map.size() * sizeof(map.front());
2641 if (!out_->WriteFully(map.data(), length)) {
2642 PLOG(ERROR) << "Failed to write quickening info for " << method_ref.PrettyMethod()
2643 << " to " << out_->GetLocation();
2644 return false;
2645 }
2646 written_bytes_ += length;
2647 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002648 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002649 offsets->push_back(offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002650 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002651 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002652 return true;
2653 }
2654
2655 size_t GetNumberOfWrittenBytes() const {
2656 return written_bytes_;
2657 }
2658
Mathieu Chartier210531f2018-01-12 10:15:51 -08002659 SafeMap<const DexFile*, std::vector<uint32_t>>& GetQuickenInfoOffsetIndicies() {
2660 return quicken_info_offset_indices_;
2661 }
2662
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002663 private:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002664 OatWriter* const writer_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002665 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002666 size_t written_bytes_ = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002667 SafeMap<const DexFile*, std::vector<uint32_t>> quicken_info_offset_indices_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002668};
2669
Mathieu Chartier210531f2018-01-12 10:15:51 -08002670class OatWriter::WriteQuickeningInfoOffsetsMethodVisitor {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002671 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002672 WriteQuickeningInfoOffsetsMethodVisitor(
2673 OutputStream* out,
2674 uint32_t start_offset,
2675 SafeMap<const DexFile*, std::vector<uint32_t>>* quicken_info_offset_indices,
2676 std::vector<uint32_t>* out_table_offsets)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002677 : out_(out),
Mathieu Chartier210531f2018-01-12 10:15:51 -08002678 start_offset_(start_offset),
2679 quicken_info_offset_indices_(quicken_info_offset_indices),
2680 out_table_offsets_(out_table_offsets) {}
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002681
Mathieu Chartier210531f2018-01-12 10:15:51 -08002682 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002683 for (const DexFile* dex_file : dex_files) {
Mathieu Chartier210531f2018-01-12 10:15:51 -08002684 auto it = quicken_info_offset_indices_->find(dex_file);
2685 DCHECK(it != quicken_info_offset_indices_->end()) << "Failed to find dex file "
2686 << dex_file->GetLocation();
2687 const std::vector<uint32_t>* const offsets = &it->second;
2688
2689 const uint32_t current_offset = start_offset_ + written_bytes_;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002690 CHECK_ALIGNED_PARAM(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002691
2692 // Generate and write the data.
2693 std::vector<uint8_t> table_data;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002694 CompactOffsetTable::Build(*offsets, &table_data);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002695
2696 // Store the offset since we need to put those after the dex file. Table offsets are relative
2697 // to the start of the quicken info section.
2698 out_table_offsets_->push_back(current_offset);
2699
2700 const uint32_t length = table_data.size() * sizeof(table_data.front());
2701 if (!out_->WriteFully(table_data.data(), length)) {
2702 PLOG(ERROR) << "Failed to write quickening offset table for " << dex_file->GetLocation()
2703 << " to " << out_->GetLocation();
2704 return false;
2705 }
2706 written_bytes_ += length;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002707 }
2708 return true;
2709 }
2710
2711 size_t GetNumberOfWrittenBytes() const {
2712 return written_bytes_;
2713 }
2714
2715 private:
2716 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002717 const uint32_t start_offset_;
2718 size_t written_bytes_ = 0u;
2719 // Maps containing the offsets for the tables.
2720 SafeMap<const DexFile*, std::vector<uint32_t>>* const quicken_info_offset_indices_;
2721 std::vector<uint32_t>* const out_table_offsets_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002722};
2723
2724bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08002725 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002726 // Nothing to write. Leave `vdex_size_` untouched and unaligned.
2727 vdex_quickening_info_offset_ = vdex_size_;
2728 size_quickening_info_alignment_ = 0;
2729 return true;
2730 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002731 size_t initial_offset = vdex_size_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002732 // Make sure the table is properly aligned.
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002733 size_t start_offset = RoundUp(initial_offset, 4u);
2734
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002735 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2736 if (actual_offset != static_cast<off_t>(start_offset)) {
2737 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2738 << " Expected: " << start_offset
2739 << " Output: " << vdex_out->GetLocation();
2740 return false;
2741 }
2742
Mathieu Chartier210531f2018-01-12 10:15:51 -08002743 size_t current_offset = start_offset;
2744 if (compiler_driver_->GetCompilerOptions().IsQuickeningCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002745 std::vector<uint32_t> dex_files_indices;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002746 WriteQuickeningInfoMethodVisitor write_quicken_info_visitor(this, vdex_out);
2747 if (!write_quicken_info_visitor.VisitDexMethods(*dex_files_)) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002748 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2749 return false;
2750 }
2751
Mathieu Chartier210531f2018-01-12 10:15:51 -08002752 uint32_t quicken_info_offset = write_quicken_info_visitor.GetNumberOfWrittenBytes();
2753 current_offset = current_offset + quicken_info_offset;
2754 uint32_t before_offset = current_offset;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002755 current_offset = RoundUp(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002756 const size_t extra_bytes = current_offset - before_offset;
2757 quicken_info_offset += extra_bytes;
2758 actual_offset = vdex_out->Seek(current_offset, kSeekSet);
2759 if (actual_offset != static_cast<off_t>(current_offset)) {
2760 PLOG(ERROR) << "Failed to seek to quickening offset table section. Actual: " << actual_offset
2761 << " Expected: " << current_offset
2762 << " Output: " << vdex_out->GetLocation();
2763 return false;
2764 }
2765
2766 std::vector<uint32_t> table_offsets;
2767 WriteQuickeningInfoOffsetsMethodVisitor table_visitor(
2768 vdex_out,
2769 quicken_info_offset,
2770 &write_quicken_info_visitor.GetQuickenInfoOffsetIndicies(),
2771 /*out*/ &table_offsets);
2772 if (!table_visitor.VisitDexMethods(*dex_files_)) {
2773 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2774 << vdex_out->GetLocation();
2775 return false;
2776 }
2777
2778 CHECK_EQ(table_offsets.size(), dex_files_->size());
2779
2780 current_offset += table_visitor.GetNumberOfWrittenBytes();
2781
2782 // Store the offset table offset as a preheader for each dex.
2783 size_t index = 0;
2784 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
2785 const off_t desired_offset = oat_dex_file.dex_file_offset_ -
2786 sizeof(VdexFile::QuickeningTableOffsetType);
2787 actual_offset = vdex_out->Seek(desired_offset, kSeekSet);
2788 if (actual_offset != desired_offset) {
2789 PLOG(ERROR) << "Failed to seek to before dex file for writing offset table offset: "
2790 << actual_offset << " Expected: " << desired_offset
2791 << " Output: " << vdex_out->GetLocation();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002792 return false;
2793 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002794 uint32_t offset = table_offsets[index];
2795 if (!vdex_out->WriteFully(reinterpret_cast<const uint8_t*>(&offset), sizeof(offset))) {
2796 PLOG(ERROR) << "Failed to write verifier deps."
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002797 << " File: " << vdex_out->GetLocation();
2798 return false;
2799 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002800 ++index;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002801 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002802 if (!vdex_out->Flush()) {
2803 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2804 << " File: " << vdex_out->GetLocation();
2805 return false;
2806 }
2807 size_quickening_info_ = current_offset - start_offset;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002808 } else {
2809 // We know we did not quicken.
2810 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002811 }
2812
David Brazdil93592f52017-12-08 10:53:27 +00002813 if (size_quickening_info_ == 0) {
2814 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2815 vdex_quickening_info_offset_ = initial_offset;
2816 size_quickening_info_alignment_ = 0;
2817 } else {
2818 vdex_size_ = start_offset + size_quickening_info_;
2819 vdex_quickening_info_offset_ = start_offset;
2820 size_quickening_info_alignment_ = start_offset - initial_offset;
2821 }
2822
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002823 return true;
2824}
2825
David Brazdil5d5a36b2016-09-14 15:34:10 +01002826bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002827 if (verifier_deps == nullptr) {
2828 // Nothing to write. Record the offset, but no need
2829 // for alignment.
2830 vdex_verifier_deps_offset_ = vdex_size_;
2831 return true;
2832 }
2833
2834 size_t initial_offset = vdex_size_;
2835 size_t start_offset = RoundUp(initial_offset, 4u);
2836
2837 vdex_size_ = start_offset;
2838 vdex_verifier_deps_offset_ = vdex_size_;
2839 size_verifier_deps_alignment_ = start_offset - initial_offset;
2840
2841 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2842 if (actual_offset != static_cast<off_t>(start_offset)) {
2843 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2844 << " Expected: " << start_offset
2845 << " Output: " << vdex_out->GetLocation();
2846 return false;
2847 }
2848
2849 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002850 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002851
2852 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2853 PLOG(ERROR) << "Failed to write verifier deps."
2854 << " File: " << vdex_out->GetLocation();
2855 return false;
2856 }
2857 if (!vdex_out->Flush()) {
2858 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2859 << " File: " << vdex_out->GetLocation();
2860 return false;
2861 }
2862
2863 size_verifier_deps_ = buffer.size();
2864 vdex_size_ += size_verifier_deps_;
2865 return true;
2866}
2867
David Srbeckybc90fd02015-04-22 19:40:27 +01002868bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002869 CHECK(write_state_ == WriteState::kWriteText);
2870
Vladimir Markoe079e212016-05-25 12:49:49 +01002871 // Wrap out to update checksum with each write.
2872 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2873 out = &checksum_updating_out;
2874
Vladimir Marko944da602016-02-19 12:27:55 +00002875 SetMultiOatRelativePatcherAdjustment();
2876
David Srbeckybc90fd02015-04-22 19:40:27 +01002877 const size_t file_offset = oat_data_offset_;
2878 size_t relative_offset = oat_header_->GetExecutableOffset();
2879 DCHECK_OFFSET();
2880
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002881 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002882 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002883 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002884 return false;
2885 }
2886
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002887 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2888 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002889 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002890 return false;
2891 }
2892
Vladimir Markob066d432018-01-03 13:14:37 +00002893 if (data_bimg_rel_ro_size_ != 0u) {
2894 write_state_ = WriteState::kWriteDataBimgRelRo;
2895 } else {
2896 if (!CheckOatSize(out, file_offset, relative_offset)) {
2897 return false;
2898 }
2899 write_state_ = WriteState::kWriteHeader;
2900 }
2901 return true;
2902}
2903
2904bool OatWriter::WriteDataBimgRelRo(OutputStream* out) {
2905 CHECK(write_state_ == WriteState::kWriteDataBimgRelRo);
2906
2907 // Wrap out to update checksum with each write.
2908 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2909 out = &checksum_updating_out;
2910
2911 const size_t file_offset = oat_data_offset_;
2912 size_t relative_offset = data_bimg_rel_ro_start_;
2913
2914 // Record the padding before the .data.bimg.rel.ro section.
2915 // Do not write anything, this zero-filled part was skipped (Seek()) when starting the section.
2916 size_t code_end = GetOatHeader().GetExecutableOffset() + code_size_;
2917 DCHECK_EQ(RoundUp(code_end, kPageSize), relative_offset);
2918 size_t padding_size = relative_offset - code_end;
2919 DCHECK_EQ(size_data_bimg_rel_ro_alignment_, 0u);
2920 size_data_bimg_rel_ro_alignment_ = padding_size;
2921
2922 relative_offset = WriteDataBimgRelRo(out, file_offset, relative_offset);
2923 if (relative_offset == 0) {
2924 LOG(ERROR) << "Failed to write boot image relocations to " << out->GetLocation();
2925 return false;
2926 }
2927
2928 if (!CheckOatSize(out, file_offset, relative_offset)) {
2929 return false;
2930 }
2931 write_state_ = WriteState::kWriteHeader;
2932 return true;
2933}
2934
2935bool OatWriter::CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002936 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002937 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002938 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2939 return false;
2940 }
2941
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002942 if (kIsDebugBuild) {
2943 uint32_t size_total = 0;
2944 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002945 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2946 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002947
David Brazdil7b49e6c2016-09-01 11:06:18 +01002948 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002949 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002950 DO_STAT(size_dex_file_alignment_);
2951 DO_STAT(size_executable_offset_alignment_);
2952 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002953 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002954 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002955 DO_STAT(size_verifier_deps_);
2956 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002957 DO_STAT(size_quickening_info_);
2958 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002959 DO_STAT(size_interpreter_to_interpreter_bridge_);
2960 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2961 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002962 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002963 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002964 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002965 DO_STAT(size_quick_to_interpreter_bridge_);
2966 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002967 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002968 DO_STAT(size_code_);
2969 DO_STAT(size_code_alignment_);
Vladimir Markob066d432018-01-03 13:14:37 +00002970 DO_STAT(size_data_bimg_rel_ro_);
2971 DO_STAT(size_data_bimg_rel_ro_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002972 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002973 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002974 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002975 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002976 DO_STAT(size_oat_dex_file_location_size_);
2977 DO_STAT(size_oat_dex_file_location_data_);
2978 DO_STAT(size_oat_dex_file_location_checksum_);
2979 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002980 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002981 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002982 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2983 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2984 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002985 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002986 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2987 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002988 DO_STAT(size_oat_lookup_table_alignment_);
2989 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002990 DO_STAT(size_oat_class_offsets_alignment_);
2991 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002992 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002993 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002994 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002995 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002996 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002997 DO_STAT(size_type_bss_mappings_);
2998 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002999 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003000
David Brazdil7b49e6c2016-09-01 11:06:18 +01003001 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
3002
3003 CHECK_EQ(vdex_size_ + oat_size_, size_total);
3004 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07003005 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003006
David Brazdil7b49e6c2016-09-01 11:06:18 +01003007 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
3008 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003009
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003010 write_state_ = WriteState::kWriteHeader;
3011 return true;
3012}
3013
3014bool OatWriter::WriteHeader(OutputStream* out,
3015 uint32_t image_file_location_oat_checksum,
3016 uintptr_t image_file_location_oat_begin,
3017 int32_t image_patch_delta) {
3018 CHECK(write_state_ == WriteState::kWriteHeader);
3019
3020 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
3021 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00003022 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003023 CHECK_EQ(image_patch_delta, 0);
3024 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
3025 } else {
3026 CHECK_ALIGNED(image_patch_delta, kPageSize);
3027 oat_header_->SetImagePatchDelta(image_patch_delta);
3028 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003029 oat_header_->UpdateChecksumWithHeaderData();
3030
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003031 const size_t file_offset = oat_data_offset_;
3032
3033 off_t current_offset = out->Seek(0, kSeekCurrent);
3034 if (current_offset == static_cast<off_t>(-1)) {
3035 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
3036 return false;
3037 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003038 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003039 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
3040 return false;
3041 }
David Srbeckybc90fd02015-04-22 19:40:27 +01003042 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003043
3044 // Flush all other data before writing the header.
3045 if (!out->Flush()) {
3046 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
3047 return false;
3048 }
3049 // Write the header.
3050 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00003051 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003052 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
3053 return false;
3054 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003055 // Flush the header data.
3056 if (!out->Flush()) {
3057 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01003058 return false;
3059 }
Vladimir Markof4da6752014-08-01 19:04:18 +01003060
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003061 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
3062 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
3063 return false;
3064 }
3065 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
3066
3067 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003068 return true;
3069}
3070
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003071size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003072 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3073 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003074 // Class offsets are required to be 4 byte aligned.
3075 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
3076 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
3077 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
3078 return 0u;
3079 }
3080 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00003081 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003082 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003083 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003084 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003085 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003086 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003087 }
3088 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003089 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003090}
3091
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003092size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003093 const bool may_have_compiled = MayHaveCompiledMethods();
3094 if (may_have_compiled) {
3095 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
3096 }
3097 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003098 // If there are any classes, the class offsets allocation aligns the offset.
3099 DCHECK_ALIGNED(relative_offset, 4u);
3100 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003101 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003102 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00003103 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003104 relative_offset += oat_class_headers_[i].SizeOf();
3105 if (may_have_compiled) {
3106 if (!oat_classes_[i].Write(this, out)) {
3107 return 0u;
3108 }
3109 relative_offset += oat_classes_[i].SizeOf();
3110 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003111 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003112 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003113}
3114
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003115size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003116 {
3117 size_t vmap_tables_offset = relative_offset;
3118 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
3119 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3120 return 0;
3121 }
3122 relative_offset = visitor.GetOffset();
3123 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003124 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003125 {
3126 size_t method_infos_offset = relative_offset;
3127 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
3128 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3129 return 0;
3130 }
3131 relative_offset = visitor.GetOffset();
3132 size_method_info_ = relative_offset - method_infos_offset;
3133 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003134
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003135 return relative_offset;
3136}
3137
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003138
Vladimir Markof3c52b42017-11-17 17:32:12 +00003139template <typename GetBssOffset>
3140size_t WriteIndexBssMapping(OutputStream* out,
3141 size_t number_of_indexes,
3142 size_t slot_size,
3143 const BitVector& indexes,
3144 GetBssOffset get_bss_offset) {
3145 // Allocate the IndexBssMapping.
3146 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
3147 number_of_indexes, slot_size, indexes, get_bss_offset);
3148 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
3149 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
3150 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
3151 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
3152 mappings->ClearPadding();
3153 // Encode the IndexBssMapping.
3154 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
3155 auto init_it = mappings->begin();
3156 bool first_index = true;
3157 for (uint32_t index : indexes.Indexes()) {
3158 size_t bss_offset = get_bss_offset(index);
3159 if (first_index) {
3160 first_index = false;
3161 encoder.Reset(index, bss_offset);
3162 } else if (!encoder.TryMerge(index, bss_offset)) {
3163 *init_it = encoder.GetEntry();
3164 ++init_it;
3165 encoder.Reset(index, bss_offset);
3166 }
3167 }
3168 // Store the last entry.
3169 *init_it = encoder.GetEntry();
3170 ++init_it;
3171 DCHECK(init_it == mappings->end());
3172
3173 if (!out->WriteFully(storage.get(), mappings_size)) {
3174 return 0u;
3175 }
3176 return mappings_size;
3177}
3178
3179size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
3180 size_t file_offset,
3181 size_t relative_offset) {
3182 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
3183 if (bss_method_entry_references_.empty() &&
3184 bss_type_entry_references_.empty() &&
3185 bss_string_entry_references_.empty()) {
3186 return relative_offset;
3187 }
3188 // If there are any classes, the class offsets allocation aligns the offset
3189 // and we cannot have method bss mappings without class offsets.
3190 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
3191 "IndexBssMapping alignment check.");
3192 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
3193
3194 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003195 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
3196 const DexFile* dex_file = (*dex_files_)[i];
3197 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00003198 auto method_it = bss_method_entry_references_.find(dex_file);
3199 if (method_it != bss_method_entry_references_.end()) {
3200 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003201 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
3202 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00003203 size_t method_mappings_size = WriteIndexBssMapping(
3204 out,
3205 dex_file->NumMethodIds(),
3206 static_cast<size_t>(pointer_size),
3207 method_indexes,
3208 [=](uint32_t index) {
3209 return bss_method_entries_.Get({dex_file, index});
3210 });
3211 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003212 return 0u;
3213 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003214 size_method_bss_mappings_ += method_mappings_size;
3215 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003216 } else {
3217 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3218 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003219
3220 auto type_it = bss_type_entry_references_.find(dex_file);
3221 if (type_it != bss_type_entry_references_.end()) {
3222 const BitVector& type_indexes = type_it->second;
3223 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3224 DCHECK_OFFSET();
3225 size_t type_mappings_size = WriteIndexBssMapping(
3226 out,
3227 dex_file->NumTypeIds(),
3228 sizeof(GcRoot<mirror::Class>),
3229 type_indexes,
3230 [=](uint32_t index) {
3231 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3232 });
3233 if (type_mappings_size == 0u) {
3234 return 0u;
3235 }
3236 size_type_bss_mappings_ += type_mappings_size;
3237 relative_offset += type_mappings_size;
3238 } else {
3239 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3240 }
3241
3242 auto string_it = bss_string_entry_references_.find(dex_file);
3243 if (string_it != bss_string_entry_references_.end()) {
3244 const BitVector& string_indexes = string_it->second;
3245 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3246 DCHECK_OFFSET();
3247 size_t string_mappings_size = WriteIndexBssMapping(
3248 out,
3249 dex_file->NumStringIds(),
3250 sizeof(GcRoot<mirror::String>),
3251 string_indexes,
3252 [=](uint32_t index) {
3253 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3254 });
3255 if (string_mappings_size == 0u) {
3256 return 0u;
3257 }
3258 size_string_bss_mappings_ += string_mappings_size;
3259 relative_offset += string_mappings_size;
3260 } else {
3261 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3262 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003263 }
3264 return relative_offset;
3265}
3266
3267size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3268 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3269
3270 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3271 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3272 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3273 DCHECK_OFFSET();
3274
3275 // Write OatDexFile.
3276 if (!oat_dex_file->Write(this, out)) {
3277 return 0u;
3278 }
3279 relative_offset += oat_dex_file->SizeOf();
3280 }
3281
3282 return relative_offset;
3283}
3284
3285size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003286 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003287 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003288
Ian Rogers848871b2013-08-05 10:56:33 -07003289 #define DO_TRAMPOLINE(field) \
3290 do { \
3291 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3292 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003293 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003294 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003295 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003296 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003297 return false; \
3298 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003299 size_ ## field += (field)->size(); \
3300 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003301 DCHECK_OFFSET(); \
3302 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003303
Ian Rogers848871b2013-08-05 10:56:33 -07003304 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003305 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003306 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003307 DO_TRAMPOLINE(quick_resolution_trampoline_);
3308 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3309 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003310 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003311 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003312}
3313
Ian Rogers3d504072014-03-01 09:16:49 -08003314size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003315 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003316 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003317 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3318 // As with InitOatCodeDexFiles, also skip the writer if
3319 // compilation was disabled.
3320 if (kOatWriterDebugOatCodeLayout) {
3321 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3322 << this << "), "
3323 << "compilation is disabled";
3324 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003325
Igor Murashkin545412b2017-08-17 15:26:54 -07003326 return relative_offset;
3327 }
3328 ScopedObjectAccess soa(Thread::Current());
3329 DCHECK(ordered_methods_ != nullptr);
3330 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3331 std::move(ordered_methods_);
3332 WriteCodeMethodVisitor visitor(this,
3333 out,
3334 file_offset,
3335 relative_offset,
3336 std::move(*ordered_methods_ptr));
3337 if (UNLIKELY(!visitor.Visit())) {
3338 return 0;
3339 }
3340 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003341
Vladimir Markob163bb72015-03-31 21:49:49 +01003342 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3343 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3344 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3345
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003346 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003347}
3348
Vladimir Markob066d432018-01-03 13:14:37 +00003349size_t OatWriter::WriteDataBimgRelRo(OutputStream* out,
3350 size_t file_offset,
3351 size_t relative_offset) {
3352 if (data_bimg_rel_ro_entries_.empty()) {
3353 return relative_offset;
3354 }
3355
3356 // Write the entire .data.bimg.rel.ro with a single WriteFully().
3357 std::vector<uint32_t> data;
3358 data.reserve(data_bimg_rel_ro_entries_.size());
3359 for (const auto& entry : data_bimg_rel_ro_entries_) {
3360 uint32_t boot_image_offset = entry.first;
3361 data.push_back(boot_image_offset);
3362 }
3363 DCHECK_EQ(data.size(), data_bimg_rel_ro_entries_.size());
3364 DCHECK_OFFSET();
3365 if (!out->WriteFully(data.data(), data.size() * sizeof(data[0]))) {
3366 PLOG(ERROR) << "Failed to write .data.bimg.rel.ro in " << out->GetLocation();
3367 return 0u;
3368 }
3369 DCHECK_EQ(size_data_bimg_rel_ro_, 0u);
3370 size_data_bimg_rel_ro_ = data.size() * sizeof(data[0]);
3371 relative_offset += size_data_bimg_rel_ro_;
3372 return relative_offset;
3373}
3374
Vladimir Marko944da602016-02-19 12:27:55 +00003375bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003376 // Get the elf file offset of the oat file.
3377 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3378 if (raw_file_offset == static_cast<off_t>(-1)) {
3379 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3380 return false;
3381 }
3382 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3383 return true;
3384}
3385
Mathieu Chartier792111c2018-02-15 13:02:15 -08003386bool OatWriter::WriteDexFiles(OutputStream* out,
3387 File* file,
3388 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003389 CopyOption copy_dex_files) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003390 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003391
Mathieu Chartier792111c2018-02-15 13:02:15 -08003392 // If extraction is enabled, only do it if not all the dex files are aligned and uncompressed.
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003393 if (copy_dex_files == CopyOption::kOnlyIfCompressed) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003394 extract_dex_files_into_vdex_ = false;
3395 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3396 if (!oat_dex_file.source_.IsZipEntry()) {
3397 extract_dex_files_into_vdex_ = true;
3398 break;
3399 }
3400 ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
3401 if (!entry->IsUncompressed() || !entry->IsAlignedToDexHeader()) {
3402 extract_dex_files_into_vdex_ = true;
3403 break;
3404 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003405 }
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003406 } else if (copy_dex_files == CopyOption::kAlways) {
3407 extract_dex_files_into_vdex_ = true;
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003408 } else {
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003409 DCHECK(copy_dex_files == CopyOption::kNever);
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003410 extract_dex_files_into_vdex_ = false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003411 }
3412
Mathieu Chartier792111c2018-02-15 13:02:15 -08003413 if (extract_dex_files_into_vdex_) {
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003414 // Add the dex section header.
3415 vdex_size_ += sizeof(VdexFile::DexSectionHeader);
3416 vdex_dex_files_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003417 // Write dex files.
3418 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3419 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
3420 return false;
3421 }
3422 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003423
3424 // Write shared dex file data section and fix up the dex file headers.
3425 vdex_dex_shared_data_offset_ = vdex_size_;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003426 uint32_t shared_data_size = 0u;
3427
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003428 if (dex_container_ != nullptr) {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003429 CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003430 DexContainer::Section* const section = dex_container_->GetDataSection();
3431 if (section->Size() > 0) {
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003432 CHECK(compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003433 const off_t existing_offset = out->Seek(0, kSeekCurrent);
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003434 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3435 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3436 << existing_offset;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003437 return false;
3438 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003439 shared_data_size = section->Size();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003440 if (!out->WriteFully(section->Begin(), shared_data_size)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003441 PLOG(ERROR) << "Failed to write shared data!";
3442 return false;
3443 }
3444 if (!out->Flush()) {
3445 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003446 return false;
3447 }
3448 // Fix up the dex headers to have correct offsets to the data section.
3449 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3450 // Overwrite the header by reading it, updating the offset, and writing it back out.
3451 DexFile::Header header;
3452 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003453 PLOG(ERROR) << "Failed to read dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003454 return false;
3455 }
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003456 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3457 // Non-compact dex file, probably failed to convert due to duplicate methods.
3458 continue;
3459 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003460 CHECK_GT(vdex_dex_shared_data_offset_, oat_dex_file.dex_file_offset_);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003461 // Offset is from the dex file base.
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003462 header.data_off_ = vdex_dex_shared_data_offset_ - oat_dex_file.dex_file_offset_;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003463 // The size should already be what part of the data buffer may be used by the dex.
3464 CHECK_LE(header.data_size_, shared_data_size);
3465 if (!file->PwriteFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003466 PLOG(ERROR) << "Failed to write dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003467 return false;
3468 }
3469 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003470 section->Clear();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003471 }
3472 dex_container_.reset();
Mathieu Chartierf1609832018-01-31 03:09:56 -08003473 } else {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003474 const uint8_t* data_begin = nullptr;
3475 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3476 DexFile::Header header;
3477 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3478 PLOG(ERROR) << "Failed to read dex header";
3479 return false;
3480 }
3481 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3482 // Non compact dex does not have shared data section.
3483 continue;
3484 }
3485 const uint32_t expected_data_off = vdex_dex_shared_data_offset_ -
3486 oat_dex_file.dex_file_offset_;
3487 if (header.data_off_ != expected_data_off) {
3488 PLOG(ERROR) << "Shared data section offset " << header.data_off_
3489 << " does not match expected value " << expected_data_off;
3490 return false;
3491 }
3492 if (oat_dex_file.source_.IsRawData()) {
3493 // Figure out the start of the shared data section so we can copy it below.
3494 const uint8_t* cur_data_begin = oat_dex_file.source_.GetRawData() + header.data_off_;
3495 if (data_begin != nullptr) {
3496 CHECK_EQ(data_begin, cur_data_begin);
Mathieu Chartierf1609832018-01-31 03:09:56 -08003497 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003498 data_begin = cur_data_begin;
3499 }
3500 // The different dex files currently can have different data sizes since
3501 // the dex writer writes them one at a time into the shared section.:w
3502 shared_data_size = std::max(shared_data_size, header.data_size_);
3503 }
3504 // If we are not updating the input vdex, write out the shared data section.
3505 if (!update_input_vdex) {
3506 const off_t existing_offset = out->Seek(0, kSeekCurrent);
3507 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3508 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3509 << existing_offset;
3510 return false;
3511 }
3512 if (!out->WriteFully(data_begin, shared_data_size)) {
3513 PLOG(ERROR) << "Failed to write shared data!";
3514 return false;
3515 }
3516 if (!out->Flush()) {
3517 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
3518 return false;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003519 }
3520 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003521 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003522 vdex_size_ += shared_data_size;
3523 size_dex_file_ += shared_data_size;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003524 } else {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003525 vdex_dex_shared_data_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003526 }
3527
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003528 return true;
3529}
3530
3531void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003532 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3533 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3534 }
3535 zipped_dex_files_.clear();
3536 zip_archives_.clear();
3537 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003538}
3539
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003540bool OatWriter::WriteDexFile(OutputStream* out,
3541 File* file,
3542 OatDexFile* oat_dex_file,
3543 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003544 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003545 return false;
3546 }
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003547 // update_input_vdex disables compact dex and layout.
Mathieu Chartier7c6f6362018-01-14 20:24:38 -08003548 if (profile_compilation_info_ != nullptr ||
3549 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
3550 CHECK(!update_input_vdex)
3551 << "We should never update the input vdex when doing dexlayout or compact dex";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003552 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3553 return false;
3554 }
3555 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003556 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003557 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003558 return false;
3559 }
3560 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003561 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003562 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003563 return false;
3564 }
3565 } else {
3566 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003567 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003568 return false;
3569 }
3570 }
3571
3572 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003573 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3574 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003575 size_dex_file_ += oat_dex_file->dex_file_size_;
3576 return true;
3577}
3578
3579bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3580 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003581 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003582 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray67169412018-01-12 09:06:14 +00003583 size_dex_file_alignment_ += start_offset - initial_offset;
Mathieu Chartier7a26f942018-01-04 18:23:55 -08003584
Mathieu Chartier210531f2018-01-12 10:15:51 -08003585 // Leave extra room for the quicken offset table offset.
3586 start_offset += sizeof(VdexFile::QuickeningTableOffsetType);
3587 // TODO: Not count the offset as part of alignment.
3588 size_dex_file_alignment_ += sizeof(VdexFile::QuickeningTableOffsetType);
3589
3590 size_t file_offset = start_offset;
3591
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003592 // Seek to the start of the dex file and flush any pending operations in the stream.
3593 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003594 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3595 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003596 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003597 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003598 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3599 return false;
3600 }
3601 if (!out->Flush()) {
3602 PLOG(ERROR) << "Failed to flush before writing dex file."
3603 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3604 return false;
3605 }
3606 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003607 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003608 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003609 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003610 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3611 return false;
3612 }
3613
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003614 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003615 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003616 return true;
3617}
3618
Jeff Hao608f2ce2016-10-19 11:17:11 -07003619bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
David Brazdil2b9c35b2018-01-12 15:44:43 +00003620 // Open dex files and write them into `out`.
3621 // Note that we only verify dex files which do not belong to the boot class path.
3622 // This is because those have been processed by `hiddenapi` and would not pass
3623 // some of the checks. No guarantees are lost, however, as `hiddenapi` verifies
3624 // the dex files prior to processing.
Jeff Hao608f2ce2016-10-19 11:17:11 -07003625 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3626 std::string error_msg;
3627 std::string location(oat_dex_file->GetLocation());
3628 std::unique_ptr<const DexFile> dex_file;
David Sehr013fd802018-01-11 22:55:24 -08003629 const ArtDexFileLoader dex_file_loader;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003630 if (oat_dex_file->source_.IsZipEntry()) {
3631 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3632 std::unique_ptr<MemMap> mem_map(
3633 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003634 if (mem_map == nullptr) {
3635 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3636 return false;
3637 }
David Sehr013fd802018-01-11 22:55:24 -08003638 dex_file = dex_file_loader.Open(location,
3639 zip_entry->GetCrc32(),
3640 std::move(mem_map),
David Brazdil2b9c35b2018-01-12 15:44:43 +00003641 /* verify */ !compiling_boot_image_,
David Sehr013fd802018-01-11 22:55:24 -08003642 /* verify_checksum */ true,
3643 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003644 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003645 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003646 int dup_fd = dup(raw_file->Fd());
3647 if (dup_fd < 0) {
3648 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3649 return false;
3650 }
David Brazdil2b9c35b2018-01-12 15:44:43 +00003651 dex_file = dex_file_loader.OpenDex(dup_fd, location,
3652 /* verify */ !compiling_boot_image_,
3653 /* verify_checksum */ true,
3654 /* mmap_shared */ false,
3655 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003656 } else {
3657 // The source data is a vdex file.
3658 CHECK(oat_dex_file->source_.IsRawData())
3659 << static_cast<size_t>(oat_dex_file->source_.GetType());
3660 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3661 // Note: The raw data has already been checked to contain the header
3662 // and all the data that the header specifies as the file size.
3663 DCHECK(raw_dex_file != nullptr);
3664 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3665 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3666 // Since the source may have had its layout changed, or may be quickened, don't verify it.
David Sehr013fd802018-01-11 22:55:24 -08003667 dex_file = dex_file_loader.Open(raw_dex_file,
3668 header->file_size_,
3669 location,
3670 oat_dex_file->dex_file_location_checksum_,
3671 nullptr,
3672 /* verify */ false,
3673 /* verify_checksum */ false,
3674 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003675 }
Jeff Haode197542017-02-03 10:48:13 -08003676 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003677 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003678 return false;
3679 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003680 Options options;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003681 options.compact_dex_level_ = compact_dex_level_;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003682 options.update_checksum_ = true;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -08003683 DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003684 const uint8_t* dex_src = nullptr;
3685 if (dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0, &dex_container_, &error_msg)) {
3686 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3687 // Dex layout can affect the size of the dex file, so we update here what we have set
3688 // when adding the dex file as a source.
3689 const UnalignedDexFileHeader* header =
3690 AsUnalignedDexFileHeader(dex_container_->GetMainSection()->Begin());
3691 oat_dex_file->dex_file_size_ = header->file_size_;
3692 dex_src = dex_container_->GetMainSection()->Begin();
3693 } else {
3694 LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
3695 // Since we failed to convert the dex, just copy the input dex.
3696 dex_src = dex_file->Begin();
3697 }
3698 if (!WriteDexFile(out, oat_dex_file, dex_src, /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003699 return false;
3700 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003701 if (dex_container_ != nullptr) {
3702 // Clear the main section in case we write more data into the container.
3703 dex_container_->GetMainSection()->Clear();
3704 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003705 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003706 return true;
3707}
3708
David Brazdil7b49e6c2016-09-01 11:06:18 +01003709bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003710 File* file,
3711 OatDexFile* oat_dex_file,
3712 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003713 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003714 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003715
3716 // Extract the dex file and get the extracted size.
3717 std::string error_msg;
3718 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3719 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3720 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3721 return false;
3722 }
3723 if (file->Flush() != 0) {
3724 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3725 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3726 return false;
3727 }
3728 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3729 if (extracted_end == static_cast<off_t>(-1)) {
3730 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3731 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3732 return false;
3733 }
3734 if (extracted_end < static_cast<off_t>(start_offset)) {
3735 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3736 << " Start: " << start_offset
3737 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3738 return false;
3739 }
3740 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3741 if (extracted_size < sizeof(DexFile::Header)) {
3742 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3743 << extracted_size << " File: " << oat_dex_file->GetLocation();
3744 return false;
3745 }
3746
3747 // Read the dex file header and extract required data to OatDexFile.
3748 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3749 if (actual_offset != static_cast<off_t>(start_offset)) {
3750 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3751 << " Expected: " << start_offset
3752 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3753 return false;
3754 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003755 if (extracted_size < oat_dex_file->dex_file_size_) {
3756 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3757 << " file size from header: " << oat_dex_file->dex_file_size_
3758 << " File: " << oat_dex_file->GetLocation();
3759 return false;
3760 }
3761
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003762 // Seek both file and stream to the end offset.
3763 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3764 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3765 if (actual_offset != static_cast<off_t>(end_offset)) {
3766 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3767 << " Expected: " << end_offset
3768 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3769 return false;
3770 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003771 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003772 if (actual_offset != static_cast<off_t>(end_offset)) {
3773 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3774 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3775 return false;
3776 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003777 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003778 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3779 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3780 return false;
3781 }
3782
3783 // If we extracted more than the size specified in the header, truncate the file.
3784 if (extracted_size > oat_dex_file->dex_file_size_) {
3785 if (file->SetLength(end_offset) != 0) {
3786 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003787 << " File: " << oat_dex_file->GetLocation()
3788 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003789 return false;
3790 }
3791 }
3792
3793 return true;
3794}
3795
David Brazdil7b49e6c2016-09-01 11:06:18 +01003796bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003797 File* file,
3798 OatDexFile* oat_dex_file,
3799 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003800 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003801 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003802
3803 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3804 if (input_offset != static_cast<off_t>(0)) {
3805 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3806 << " Expected: 0"
3807 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3808 return false;
3809 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003810
3811 // Copy the input dex file using sendfile().
3812 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3813 PLOG(ERROR) << "Failed to copy dex file to oat file."
3814 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3815 return false;
3816 }
3817 if (file->Flush() != 0) {
3818 PLOG(ERROR) << "Failed to flush dex file."
3819 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3820 return false;
3821 }
3822
3823 // Check file position and seek the stream to the end offset.
3824 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3825 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3826 if (actual_offset != static_cast<off_t>(end_offset)) {
3827 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3828 << " Expected: " << end_offset
3829 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3830 return false;
3831 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003832 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003833 if (actual_offset != static_cast<off_t>(end_offset)) {
3834 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3835 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3836 return false;
3837 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003838 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003839 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3840 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3841 return false;
3842 }
3843
3844 return true;
3845}
3846
David Brazdil7b49e6c2016-09-01 11:06:18 +01003847bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003848 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003849 const uint8_t* dex_file,
3850 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003851 // Note: The raw data has already been checked to contain the header
3852 // and all the data that the header specifies as the file size.
3853 DCHECK(dex_file != nullptr);
3854 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3855 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3856
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003857 if (update_input_vdex) {
3858 // The vdex already contains the dex code, no need to write it again.
3859 } else {
3860 if (!out->WriteFully(dex_file, header->file_size_)) {
3861 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3862 << " to " << out->GetLocation();
3863 return false;
3864 }
3865 if (!out->Flush()) {
3866 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3867 << " File: " << oat_dex_file->GetLocation();
3868 return false;
3869 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003870 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003871 return true;
3872}
3873
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003874bool OatWriter::OpenDexFiles(
3875 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003876 bool verify,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003877 /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003878 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3879 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3880
3881 if (oat_dex_files_.empty()) {
3882 // Nothing to do.
3883 return true;
3884 }
3885
Mathieu Chartier792111c2018-02-15 13:02:15 -08003886 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003887 std::vector<std::unique_ptr<const DexFile>> dex_files;
3888 std::vector<std::unique_ptr<MemMap>> maps;
3889 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3890 std::string error_msg;
Mathieu Chartier792111c2018-02-15 13:02:15 -08003891 MemMap* map = oat_dex_file.source_.GetZipEntry()->MapDirectlyOrExtract(
3892 oat_dex_file.dex_file_location_data_, "zipped dex", &error_msg);
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003893 if (map == nullptr) {
3894 LOG(ERROR) << error_msg;
3895 return false;
3896 }
3897 maps.emplace_back(map);
3898 // Now, open the dex file.
3899 const ArtDexFileLoader dex_file_loader;
3900 dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
3901 map->Size(),
3902 oat_dex_file.GetLocation(),
3903 oat_dex_file.dex_file_location_checksum_,
3904 /* oat_dex_file */ nullptr,
3905 verify,
3906 verify,
3907 &error_msg));
3908 if (dex_files.back() == nullptr) {
3909 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3910 << " Error: " << error_msg;
3911 return false;
3912 }
3913 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3914 }
3915 *opened_dex_files_map = std::move(maps);
3916 *opened_dex_files = std::move(dex_files);
3917 CloseSources();
3918 return true;
3919 }
3920 // We could have closed the sources at the point of writing the dex files, but to
3921 // make it consistent with the case we're not writing the dex files, we close them now.
3922 CloseSources();
3923
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003924 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003925 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003926
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003927 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003928 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3929 length,
3930 PROT_READ | PROT_WRITE,
3931 MAP_SHARED,
3932 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003933 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003934 /* low_4gb */ false,
3935 file->GetPath().c_str(),
3936 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003937 if (dex_files_map == nullptr) {
3938 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3939 << " error: " << error_msg;
3940 return false;
3941 }
David Sehr013fd802018-01-11 22:55:24 -08003942 const ArtDexFileLoader dex_file_loader;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003943 std::vector<std::unique_ptr<const DexFile>> dex_files;
3944 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003945 const uint8_t* raw_dex_file =
3946 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003947
3948 if (kIsDebugBuild) {
3949 // Sanity check our input files.
3950 // Note that ValidateDexFileHeader() logs error messages.
3951 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3952 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003953 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3954 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003955
3956 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3957 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3958 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003959 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3960 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003961 }
3962
3963 // Now, open the dex file.
David Sehr013fd802018-01-11 22:55:24 -08003964 dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
3965 oat_dex_file.dex_file_size_,
3966 oat_dex_file.GetLocation(),
3967 oat_dex_file.dex_file_location_checksum_,
3968 /* oat_dex_file */ nullptr,
3969 verify,
3970 verify,
3971 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003972 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003973 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3974 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003975 return false;
3976 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003977
3978 // Set the class_offsets size now that we have easy access to the DexFile and
David Sehr013fd802018-01-11 22:55:24 -08003979 // it has been verified in dex_file_loader.Open.
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003980 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003981 }
3982
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003983 opened_dex_files_map->push_back(std::move(dex_files_map));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003984 *opened_dex_files = std::move(dex_files);
3985 return true;
3986}
3987
3988bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003989 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003990 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3991 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3992
David Brazdil7b49e6c2016-09-01 11:06:18 +01003993 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3994 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3995 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3996 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3997 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3998 return false;
3999 }
4000
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004001 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
4002 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
4003 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00004004 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
4005
4006 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
4007 oat_dex_file->class_offsets_.empty()) {
4008 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004009 }
David Brazdil181e1cc2016-09-01 16:38:47 +00004010
4011 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
4012 if (table_size == 0u) {
4013 continue;
4014 }
4015
4016 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07004017 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004018 const DexFile& dex_file = *opened_dex_files[i];
4019 {
4020 std::unique_ptr<TypeLookupTable> type_lookup_table =
4021 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
4022 type_lookup_table_oat_dex_files_.push_back(
4023 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
4024 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
4025 }
4026 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00004027
4028 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01004029 size_t initial_offset = oat_size_;
4030 size_t rodata_offset = RoundUp(initial_offset, 4);
4031 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00004032
4033 if (padding_size != 0u) {
4034 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01004035 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00004036 PLOG(ERROR) << "Failed to write lookup table alignment padding."
4037 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01004038 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00004039 return false;
4040 }
4041 }
4042
4043 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01004044 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00004045 DCHECK_EQ(table_size, table->RawDataLength());
4046
David Brazdil7b49e6c2016-09-01 11:06:18 +01004047 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00004048 PLOG(ERROR) << "Failed to write lookup table."
4049 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01004050 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00004051 return false;
4052 }
4053
4054 oat_dex_file->lookup_table_offset_ = rodata_offset;
4055
David Brazdil7b49e6c2016-09-01 11:06:18 +01004056 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00004057 size_oat_lookup_table_ += table_size;
4058 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004059 }
4060
David Brazdil7b49e6c2016-09-01 11:06:18 +01004061 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00004062 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01004063 << " File: " << oat_rodata->GetLocation();
4064 return false;
4065 }
4066
4067 return true;
4068}
4069
Mathieu Chartier120aa282017-08-05 16:03:03 -07004070bool OatWriter::WriteDexLayoutSections(
4071 OutputStream* oat_rodata,
4072 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
4073 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
4074
4075 if (!kWriteDexLayoutInfo) {
4076 return true;;
4077 }
4078
4079 uint32_t expected_offset = oat_data_offset_ + oat_size_;
4080 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
4081 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
4082 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
4083 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
4084 return false;
4085 }
4086
4087 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
4088 size_t rodata_offset = oat_size_;
4089 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
4090 OatDexFile* oat_dex_file = &oat_dex_files_[i];
4091 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
4092
4093 // Write dex layout section alignment bytes.
4094 const size_t padding_size =
4095 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
4096 if (padding_size != 0u) {
4097 std::vector<uint8_t> buffer(padding_size, 0u);
4098 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
4099 PLOG(ERROR) << "Failed to write lookup table alignment padding."
4100 << " File: " << oat_dex_file->GetLocation()
4101 << " Output: " << oat_rodata->GetLocation();
4102 return false;
4103 }
4104 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
4105 rodata_offset += padding_size;
4106 }
4107
4108 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
4109 DCHECK_EQ(oat_data_offset_ + rodata_offset,
4110 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
4111 DCHECK(oat_dex_file != nullptr);
4112 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
4113 sizeof(oat_dex_file->dex_sections_layout_))) {
4114 PLOG(ERROR) << "Failed to write dex layout sections."
4115 << " File: " << oat_dex_file->GetLocation()
4116 << " Output: " << oat_rodata->GetLocation();
4117 return false;
4118 }
4119 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
4120 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
4121 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
4122 }
4123 oat_size_ = rodata_offset;
4124
4125 if (!oat_rodata->Flush()) {
4126 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
4127 << " File: " << oat_rodata->GetLocation();
4128 return false;
4129 }
4130
4131 return true;
4132}
4133
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004134bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004135 // Write checksums
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004136 off_t checksums_offset = sizeof(VdexFile::VerifierDepsHeader);
4137 off_t actual_offset = vdex_out->Seek(checksums_offset, kSeekSet);
4138 if (actual_offset != checksums_offset) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004139 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
4140 << " File: " << vdex_out->GetLocation();
4141 return false;
4142 }
4143
4144 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
4145 OatDexFile* oat_dex_file = &oat_dex_files_[i];
4146 if (!vdex_out->WriteFully(
4147 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
4148 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
4149 << vdex_out->GetLocation();
4150 return false;
4151 }
4152 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
4153 }
4154
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004155 // Maybe write dex section header.
4156 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
4157 DCHECK_NE(vdex_quickening_info_offset_, 0u);
4158
4159 bool has_dex_section = extract_dex_files_into_vdex_;
4160 if (has_dex_section) {
4161 DCHECK_NE(vdex_dex_files_offset_, 0u);
4162 size_t dex_section_size = vdex_dex_shared_data_offset_ - vdex_dex_files_offset_;
4163 size_t dex_shared_data_size = vdex_verifier_deps_offset_ - vdex_dex_shared_data_offset_;
4164 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
4165
4166 VdexFile::DexSectionHeader dex_section_header(dex_section_size,
4167 dex_shared_data_size,
4168 quickening_info_section_size);
4169 if (!vdex_out->WriteFully(&dex_section_header, sizeof(VdexFile::DexSectionHeader))) {
4170 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
4171 return false;
4172 }
4173 size_vdex_header_ += sizeof(VdexFile::DexSectionHeader);
4174 }
4175
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004176 // Write header.
4177 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01004178 if (actual_offset != 0) {
4179 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
4180 << " File: " << vdex_out->GetLocation();
4181 return false;
4182 }
4183
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01004184 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01004185
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004186 VdexFile::VerifierDepsHeader deps_header(
4187 oat_dex_files_.size(), verifier_deps_section_size, has_dex_section);
4188 if (!vdex_out->WriteFully(&deps_header, sizeof(VdexFile::VerifierDepsHeader))) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01004189 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004190 return false;
4191 }
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004192 size_vdex_header_ += sizeof(VdexFile::VerifierDepsHeader);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004193
David Brazdil5d5a36b2016-09-14 15:34:10 +01004194 if (!vdex_out->Flush()) {
4195 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
4196 << " File: " << vdex_out->GetLocation();
4197 return false;
4198 }
4199
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004200 return true;
4201}
4202
Vladimir Markof4da6752014-08-01 19:04:18 +01004203bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004204 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
4205}
4206
4207bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004208 static const uint8_t kPadding[] = {
4209 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
4210 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004211 DCHECK_LE(size, sizeof(kPadding));
4212 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004213 return false;
4214 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004215 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01004216 return true;
4217}
4218
Vladimir Marko944da602016-02-19 12:27:55 +00004219void OatWriter::SetMultiOatRelativePatcherAdjustment() {
4220 DCHECK(dex_files_ != nullptr);
4221 DCHECK(relative_patcher_ != nullptr);
4222 DCHECK_NE(oat_data_offset_, 0u);
4223 if (image_writer_ != nullptr && !dex_files_->empty()) {
4224 // The oat data begin may not be initialized yet but the oat file offset is ready.
4225 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
4226 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
4227 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01004228 }
4229}
4230
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004231OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
4232 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004233 CreateTypeLookupTable create_type_lookup_table,
4234 uint32_t dex_file_location_checksum,
4235 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004236 : source_(source),
4237 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004238 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004239 offset_(0),
4240 dex_file_location_size_(strlen(dex_file_location)),
4241 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004242 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004243 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004244 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004245 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00004246 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00004247 type_bss_mapping_offset_(0u),
4248 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004249 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004250 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07004251}
4252
4253size_t OatWriter::OatDexFile::SizeOf() const {
4254 return sizeof(dex_file_location_size_)
4255 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08004256 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08004257 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004258 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004259 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004260 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00004261 + sizeof(type_bss_mapping_offset_)
4262 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004263 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004264}
4265
4266bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
4267 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08004268 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004269
Vladimir Markoe079e212016-05-25 12:49:49 +01004270 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004271 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004272 return false;
4273 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004274 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004275
Vladimir Markoe079e212016-05-25 12:49:49 +01004276 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004277 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004278 return false;
4279 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004280 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004281
Vladimir Markoe079e212016-05-25 12:49:49 +01004282 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004283 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004284 return false;
4285 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004286 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004287
Vladimir Markoe079e212016-05-25 12:49:49 +01004288 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004289 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08004290 return false;
4291 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004292 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004293
Vladimir Markoe079e212016-05-25 12:49:49 +01004294 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004295 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
4296 return false;
4297 }
4298 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
4299
Vladimir Markoe079e212016-05-25 12:49:49 +01004300 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03004301 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
4302 return false;
4303 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004304 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004305
Mathieu Chartier120aa282017-08-05 16:03:03 -07004306 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4307 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4308 return false;
4309 }
4310 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4311
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004312 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4313 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4314 return false;
4315 }
4316 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4317
Vladimir Markof3c52b42017-11-17 17:32:12 +00004318 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4319 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4320 return false;
4321 }
4322 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4323
4324 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4325 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4326 return false;
4327 }
4328 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4329
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004330 return true;
4331}
4332
4333bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004334 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004335 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4336 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004337 return false;
4338 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004339 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004340 return true;
4341}
4342
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004343OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004344 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004345 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004346 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004347 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004348 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004349
Brian Carlstromba150c32013-08-27 17:31:03 -07004350 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4351
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004352 method_offsets_.resize(compiled_methods_with_code);
4353 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004354
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004355 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4356 // We only create this instance if there are at least some compiled.
4357 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004358 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004359 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4360 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4361 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4362 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004363 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004364 method_bitmap_size_ = 0;
4365 }
4366
4367 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004368 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004369 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004370 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4371 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004372 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004373 method_bitmap_->SetBit(i);
4374 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004375 } else {
4376 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004377 }
4378 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004379}
4380
Brian Carlstrom265091e2013-01-30 14:08:26 -08004381size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004382 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004383 + method_bitmap_size_
4384 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004385}
4386
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004387bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4388 OutputStream* out,
4389 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004390 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004391 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004392 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004393 return false;
4394 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004395 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004396
Vladimir Markoe079e212016-05-25 12:49:49 +01004397 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004398 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004399 return false;
4400 }
4401 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004402 return true;
4403}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004404
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004405bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004406 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004407 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004408 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004409 return false;
4410 }
4411 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004412
Vladimir Markoe079e212016-05-25 12:49:49 +01004413 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004414 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004415 return false;
4416 }
4417 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4418 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004419
Vladimir Markoe079e212016-05-25 12:49:49 +01004420 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004421 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004422 return false;
4423 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004424 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004425 return true;
4426}
4427
David Srbecky32210b92017-12-04 14:39:21 +00004428debug::DebugInfo OatWriter::GetDebugInfo() const {
4429 debug::DebugInfo debug_info{};
4430 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
David Srbecky96c84462018-02-05 15:42:40 +00004431 if (VdexWillContainDexFiles()) {
David Srbecky25931622018-01-18 22:55:20 +00004432 DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
4433 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
4434 const DexFile* dex_file = (*dex_files_)[i];
4435 const OatDexFile& oat_dex_file = oat_dex_files_[i];
David Srbecky96c84462018-02-05 15:42:40 +00004436 uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
4437 if (dex_file_offset != 0) {
4438 debug_info.dex_files.emplace(dex_file_offset, dex_file);
4439 }
David Srbecky32210b92017-12-04 14:39:21 +00004440 }
4441 }
4442 return debug_info;
4443}
4444
Vladimir Marko74527972016-11-29 15:57:32 +00004445} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004446} // namespace art