blob: 065e31a01e7949a42027875f515b6a23a8cc2b78 [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"
David Sehr79e26072018-04-06 17:58:50 -070034#include "base/zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070035#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010036#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010037#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000038#include "debug/method_debug_info.h"
David Sehr013fd802018-01-11 22:55:24 -080039#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080040#include "dex/dex_file-inl.h"
41#include "dex/dex_file_loader.h"
42#include "dex/dex_file_types.h"
43#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070044#include "dex/type_lookup_table.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000045#include "dex/verification_results.h"
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080046#include "dex_container.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070047#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070048#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000049#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010050#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030052#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010053#include "image_writer.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"
David Sehr82d046e2018-04-23 08:14:19 -070065#include "profile/profile_compilation_info.h"
Mathieu Chartier210531f2018-01-12 10:15:51 -080066#include "quicken_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070067#include "scoped_thread_state_change-inl.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010068#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010069#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010070#include "verifier/verifier_deps.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
Vladimir Markoa0431112018-06-25 09:32:54 +0100358OatWriter::OatWriter(const CompilerOptions& compiler_options,
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700359 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),
Vladimir Markoa0431112018-06-25 09:32:54 +0100369 compiler_options_(compiler_options),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000370 image_writer_(nullptr),
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 {
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100645 return GetCompilerOptions().IsAnyCompilationEnabled();
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700646}
647
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000648bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100649 File* vdex_file,
650 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000651 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800652 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000653 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +0000654 CopyOption copy_dex_files,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000655 /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000656 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
657 CHECK(write_state_ == WriteState::kAddingDexFileSources);
658
David Brazdil7b49e6c2016-09-01 11:06:18 +0100659 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
660 if (!RecordOatDataOffset(oat_rodata)) {
661 return false;
662 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000663
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000664 std::vector<std::unique_ptr<MemMap>> dex_files_map;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000665 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100666
667 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000668
669 // Reserve space for Vdex header and checksums.
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000670 vdex_size_ = sizeof(VdexFile::VerifierDepsHeader) +
671 oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Markoa0431112018-06-25 09:32:54 +0100672 oat_size_ = InitOatHeader(dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100673 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100674
675 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
676
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000677 std::unique_ptr<BufferedOutputStream> vdex_out =
678 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
679 // Write DEX files into VDEX, mmap and open them.
Mathieu Chartier792111c2018-02-15 13:02:15 -0800680 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex, copy_dex_files) ||
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000681 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
682 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000683 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000684
Mathieu Chartier120aa282017-08-05 16:03:03 -0700685 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000686 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
687 return false;
688 }
689
Mathieu Chartier120aa282017-08-05 16:03:03 -0700690 // Write dex layout sections into the oat file.
691 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
692 return false;
693 }
694
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000695 *opened_dex_files_map = std::move(dex_files_map);
696 *opened_dex_files = std::move(dex_files);
697 write_state_ = WriteState::kPrepareLayout;
698 return true;
699}
700
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100701// Initialize the writer with the given parameters.
702void OatWriter::Initialize(const CompilerDriver* compiler_driver,
703 ImageWriter* image_writer,
704 const std::vector<const DexFile*>& dex_files) {
705 compiler_driver_ = compiler_driver;
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100706 image_writer_ = image_writer;
707 dex_files_ = &dex_files;
708}
709
Vladimir Marko74527972016-11-29 15:57:32 +0000710void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000711 CHECK(write_state_ == WriteState::kPrepareLayout);
712
Vladimir Marko944da602016-02-19 12:27:55 +0000713 relative_patcher_ = relative_patcher;
714 SetMultiOatRelativePatcherAdjustment();
715
Vladimir Markoa0431112018-06-25 09:32:54 +0100716 if (GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000717 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800718 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100719 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000720 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100721
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100722 {
723 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
724 InitBssLayout(instruction_set);
725 }
726
David Brazdil7b49e6c2016-09-01 11:06:18 +0100727 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800728 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100729 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
730 offset = InitClassOffsets(offset);
731 }
732 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000733 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800734 offset = InitOatClasses(offset);
735 }
736 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000737 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
738 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100739 }
740 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000741 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100742 offset = InitOatMaps(offset);
743 }
744 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100745 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
746 oat_header_->SetOatDexFilesOffset(offset);
747 offset = InitOatDexFiles(offset);
748 }
749 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000750 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800751 offset = InitOatCode(offset);
752 }
753 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000754 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800755 offset = InitOatCodeDexFiles(offset);
Vladimir Markob066d432018-01-03 13:14:37 +0000756 code_size_ = offset - GetOatHeader().GetExecutableOffset();
Ian Rogersca368cb2013-11-15 15:52:08 -0800757 }
Vladimir Markob066d432018-01-03 13:14:37 +0000758 {
759 TimingLogger::ScopedTiming split("InitDataBimgRelRoLayout", timings_);
760 offset = InitDataBimgRelRoLayout(offset);
761 }
762 oat_size_ = offset; // .bss does not count towards oat_size_.
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100763 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100764
Brian Carlstrome24fa612011-09-29 00:53:55 -0700765 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Markoa0431112018-06-25 09:32:54 +0100766 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800767 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000768 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800769 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000770
771 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700772}
773
Ian Rogers0571d352011-11-03 19:51:38 -0700774OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700775}
776
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100777class OatWriter::DexMethodVisitor {
778 public:
779 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100780 : writer_(writer),
781 offset_(offset),
782 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700783 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100784
785 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
786 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700787 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100788 dex_file_ = dex_file;
789 class_def_index_ = class_def_index;
790 return true;
791 }
792
793 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
794
795 virtual bool EndClass() {
796 if (kIsDebugBuild) {
797 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700798 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100799 }
800 return true;
801 }
802
803 size_t GetOffset() const {
804 return offset_;
805 }
806
807 protected:
808 virtual ~DexMethodVisitor() { }
809
810 OatWriter* const writer_;
811
812 // The offset is usually advanced for each visited method by the derived class.
813 size_t offset_;
814
815 // The dex file and class def index are set in StartClass().
816 const DexFile* dex_file_;
817 size_t class_def_index_;
818};
819
820class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
821 public:
822 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100823 : DexMethodVisitor(writer, offset),
824 oat_class_index_(0u),
825 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100826
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100827 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100828 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700829 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
830 // There are no oat classes if there aren't any compiled methods.
831 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
832 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833 method_offsets_index_ = 0u;
834 return true;
835 }
836
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100837 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100838 ++oat_class_index_;
839 return DexMethodVisitor::EndClass();
840 }
841
842 protected:
843 size_t oat_class_index_;
844 size_t method_offsets_index_;
845};
846
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100847static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000848 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100849}
850
851static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000852 // The dextodexcompiler puts the quickening info table into the CompiledMethod
853 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100854 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
855}
856
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100857class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
858 public:
859 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
860 : DexMethodVisitor(writer, /* offset */ 0u) {}
861
862 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
863 const ClassDataItemIterator& it) OVERRIDE {
864 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
865 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
866 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100867 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100868 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Markob066d432018-01-03 13:14:37 +0000869 if (patch.GetType() == LinkerPatch::Type::kDataBimgRelRo) {
870 writer_->data_bimg_rel_ro_entries_.Overwrite(patch.BootImageOffset(),
871 /* placeholder */ 0u);
872 } else if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100873 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000874 AddBssReference(target_method,
875 target_method.dex_file->NumMethodIds(),
876 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100877 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
878 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000879 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
880 AddBssReference(target_type,
881 target_type.dex_file->NumTypeIds(),
882 &writer_->bss_type_entry_references_);
883 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100884 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000885 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
886 AddBssReference(target_string,
887 target_string.dex_file->NumStringIds(),
888 &writer_->bss_string_entry_references_);
889 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100890 }
891 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100892 } else {
893 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100894 }
895 return true;
896 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000897
898 private:
899 void AddBssReference(const DexFileReference& ref,
900 size_t number_of_indexes,
901 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
902 // We currently support inlining of throwing instructions only when they originate in the
903 // same dex file as the outer method. All .bss references are used by throwing instructions.
904 DCHECK_EQ(dex_file_, ref.dex_file);
905
906 auto refs_it = references->find(ref.dex_file);
907 if (refs_it == references->end()) {
908 refs_it = references->Put(
909 ref.dex_file,
910 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
911 refs_it->second.ClearAllBits();
912 }
913 refs_it->second.SetBit(ref.index);
914 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100915};
916
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100917class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
918 public:
919 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100920 : DexMethodVisitor(writer, offset),
921 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100922 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000923 size_t num_classes = 0u;
924 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
925 num_classes += oat_dex_file.class_offsets_.size();
926 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700927 // If we aren't compiling only reserve headers.
928 writer_->oat_class_headers_.reserve(num_classes);
929 if (writer->MayHaveCompiledMethods()) {
930 writer->oat_classes_.reserve(num_classes);
931 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100932 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100933 // If there are any classes, the class offsets allocation aligns the offset.
934 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100935 }
936
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100937 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100938 DexMethodVisitor::StartClass(dex_file, class_def_index);
939 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100940 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941 return true;
942 }
943
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300944 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100945 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100946 // Fill in the compiled_methods_ array for methods that have a
947 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100948 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100949 // OatMethodOffsets for the compiled methods.
950 uint32_t method_idx = it.GetMemberIndex();
951 CompiledMethod* compiled_method =
952 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
953 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100954 if (HasCompiledCode(compiled_method)) {
955 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100956 }
957 return true;
958 }
959
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100960 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100961 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko2c64a832018-01-04 11:31:56 +0000962 ClassStatus status;
Andreas Gampebb846102017-05-11 21:03:35 -0700963 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
964 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700965 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
966 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700967 // The oat class status is used only for verification of resolved classes,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000968 // so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
Andreas Gampebb846102017-05-11 21:03:35 -0700969 // during compile-time verification.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000970 status = ClassStatus::kErrorResolved;
Andreas Gampebb846102017-05-11 21:03:35 -0700971 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +0000972 status = ClassStatus::kNotReady;
Andreas Gampebb846102017-05-11 21:03:35 -0700973 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100974 }
975
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700976 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100977 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700978 compiled_methods_.size(),
979 status);
980 OatClassHeader& header = writer_->oat_class_headers_.back();
981 offset_ += header.SizeOf();
982 if (writer_->MayHaveCompiledMethods()) {
983 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100984 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700985 header.type_);
986 offset_ += writer_->oat_classes_.back().SizeOf();
987 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100988 return DexMethodVisitor::EndClass();
989 }
990
991 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000992 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100993 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100994};
995
Igor Murashkin545412b2017-08-17 15:26:54 -0700996// CompiledMethod + metadata required to do ordered method layout.
997//
998// See also OrderedMethodVisitor.
999struct OatWriter::OrderedMethodData {
1000 ProfileCompilationInfo::MethodHotness method_hotness;
1001 OatClass* oat_class;
1002 CompiledMethod* compiled_method;
1003 MethodReference method_reference;
1004 size_t method_offsets_index;
1005
1006 size_t class_def_index;
1007 uint32_t access_flags;
1008 const DexFile::CodeItem* code_item;
1009
1010 // A value of -1 denotes missing debug info
1011 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
1012 // Index into writer_->method_info_
1013 size_t debug_info_idx;
1014
1015 bool HasDebugInfo() const {
1016 return debug_info_idx != kDebugInfoIdxInvalid;
1017 }
1018
1019 // Bin each method according to the profile flags.
1020 //
1021 // Groups by e.g.
1022 // -- not hot at all
1023 // -- hot
1024 // -- hot and startup
1025 // -- hot and post-startup
1026 // -- hot and startup and poststartup
1027 // -- startup
1028 // -- startup and post-startup
1029 // -- post-startup
1030 //
1031 // (See MethodHotness enum definition for up-to-date binning order.)
1032 bool operator<(const OrderedMethodData& other) const {
1033 if (kOatWriterForceOatCodeLayout) {
1034 // Development flag: Override default behavior by sorting by name.
1035
1036 std::string name = method_reference.PrettyMethod();
1037 std::string other_name = other.method_reference.PrettyMethod();
1038 return name < other_name;
1039 }
1040
1041 // Use the profile's method hotness to determine sort order.
1042 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1043 return true;
1044 }
1045
1046 // Default: retain the original order.
1047 return false;
1048 }
1049
1050 private:
1051 // Used to determine relative order for OAT code layout when determining
1052 // binning.
1053 size_t GetMethodHotnessOrder() const {
1054 bool hotness[] = {
1055 method_hotness.IsHot(),
1056 method_hotness.IsStartup(),
1057 method_hotness.IsPostStartup()
1058 };
1059
1060
1061 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1062 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1063 // time that memory is referenced in the process.
1064
1065 size_t hotness_bits = 0;
1066 for (size_t i = 0; i < arraysize(hotness); ++i) {
1067 if (hotness[i]) {
1068 hotness_bits |= (1 << i);
1069 }
1070 }
1071
1072 if (kIsDebugBuild) {
1073 // Check for bins that are always-empty given a real profile.
1074 if (method_hotness.IsHot() &&
1075 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1076 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001077 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1078 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001079 // This is not fatal, so only warn.
1080 }
1081 }
1082
1083 return hotness_bits;
1084 }
1085};
1086
1087// Given a queue of CompiledMethod in some total order,
1088// visit each one in that order.
1089class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001090 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001091 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1092 : ordered_methods_(std::move(ordered_methods)) {
1093 }
1094
1095 virtual ~OrderedMethodVisitor() {}
1096
1097 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1098 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1099 if (!VisitStart()) {
1100 return false;
1101 }
1102
1103 for (const OrderedMethodData& method_data : ordered_methods_) {
1104 if (!VisitMethod(method_data)) {
1105 return false;
1106 }
1107 }
1108
1109 return VisitComplete();
1110 }
1111
1112 // Invoked once at the beginning, prior to visiting anything else.
1113 //
1114 // Return false to abort further visiting.
1115 virtual bool VisitStart() { return true; }
1116
1117 // Invoked repeatedly in the order specified by `ordered_methods`.
1118 //
1119 // Return false to short-circuit and to stop visiting further methods.
1120 virtual bool VisitMethod(const OrderedMethodData& method_data)
1121 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1122
1123 // Invoked once at the end, after every other method has been successfully visited.
1124 //
1125 // Return false to indicate the overall `Visit` has failed.
1126 virtual bool VisitComplete() = 0;
1127
1128 OrderedMethodList ReleaseOrderedMethods() {
1129 return std::move(ordered_methods_);
1130 }
1131
1132 private:
1133 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1134 // Methods can be inserted more than once in case of duplicated methods.
1135 OrderedMethodList ordered_methods_;
1136};
1137
1138// Visit every compiled method in order to determine its order within the OAT file.
1139// Methods from the same class do not need to be adjacent in the OAT code.
1140class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1141 public:
1142 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1143 : OatDexMethodVisitor(writer, offset) {
1144 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001145
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001146 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001147 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001148 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001149 }
1150
Igor Murashkin545412b2017-08-17 15:26:54 -07001151 bool VisitMethod(size_t class_def_method_index,
1152 const ClassDataItemIterator& it)
1153 OVERRIDE
1154 REQUIRES_SHARED(Locks::mutator_lock_) {
1155 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1156
Vladimir Marko49b0f452015-12-10 13:49:19 +00001157 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001158 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1159
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001160 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001161 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001162
Igor Murashkin545412b2017-08-17 15:26:54 -07001163 {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001164 const CompilerOptions& compiler_options = writer_->GetCompilerOptions();
Igor Murashkin545412b2017-08-17 15:26:54 -07001165 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1166 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001167
Igor Murashkin545412b2017-08-17 15:26:54 -07001168 // Debug method info must be pushed in the original order
1169 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1170 // ElfCompilationUnitWriter::Write requires this.
1171 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1172 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1173 writer_->method_info_.push_back(info);
1174
1175 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1176 // once we know the offsets.
1177 //
1178 // Store the index into writer_->method_info_ since future push-backs
1179 // could reallocate and change the underlying data address.
1180 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001181 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001182 }
1183
1184 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1185
1186 // Lookup method hotness from profile, if available.
1187 // Otherwise assume a default of none-hotness.
1188 ProfileCompilationInfo::MethodHotness method_hotness =
1189 writer_->profile_compilation_info_ != nullptr
1190 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1191 : ProfileCompilationInfo::MethodHotness();
1192
1193 // Handle duplicate methods by pushing them repeatedly.
1194 OrderedMethodData method_data = {
1195 method_hotness,
1196 oat_class,
1197 compiled_method,
1198 method_ref,
1199 method_offsets_index_,
1200 class_def_index_,
1201 it.GetMethodAccessFlags(),
1202 it.GetMethodCodeItem(),
1203 debug_info_idx
1204 };
1205 ordered_methods_.push_back(method_data);
1206
1207 method_offsets_index_++;
1208 }
1209
1210 return true;
1211 }
1212
1213 OrderedMethodList ReleaseOrderedMethods() {
1214 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1215 // Sort by the method ordering criteria (in OrderedMethodData).
1216 // Since most methods will have the same ordering criteria,
1217 // we preserve the original insertion order within the same sort order.
1218 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1219 } else {
1220 // The profile-less behavior is as if every method had 0 hotness
1221 // associated with it.
1222 //
1223 // Since sorting all methods with hotness=0 should give back the same
1224 // order as before, don't do anything.
1225 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1226 }
1227
1228 return std::move(ordered_methods_);
1229 }
1230
1231 private:
1232 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1233 // Methods can be inserted more than once in case of duplicated methods.
1234 OrderedMethodList ordered_methods_;
1235};
1236
1237// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1238class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1239 public:
1240 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1241 size_t offset,
1242 OrderedMethodList ordered_methods)
1243 : LayoutReserveOffsetCodeMethodVisitor(writer,
1244 offset,
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001245 writer->GetCompilerOptions(),
Igor Murashkin545412b2017-08-17 15:26:54 -07001246 std::move(ordered_methods)) {
1247 }
1248
1249 virtual bool VisitComplete() OVERRIDE {
1250 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1251 if (generate_debug_info_) {
1252 std::vector<debug::MethodDebugInfo> thunk_infos =
1253 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1254 writer_->method_info_.insert(writer_->method_info_.end(),
1255 std::make_move_iterator(thunk_infos.begin()),
1256 std::make_move_iterator(thunk_infos.end()));
1257 }
1258 return true;
1259 }
1260
1261 virtual bool VisitMethod(const OrderedMethodData& method_data)
1262 OVERRIDE
1263 REQUIRES_SHARED(Locks::mutator_lock_) {
1264 OatClass* oat_class = method_data.oat_class;
1265 CompiledMethod* compiled_method = method_data.compiled_method;
1266 const MethodReference& method_ref = method_data.method_reference;
1267 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1268 size_t class_def_index = method_data.class_def_index;
1269 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001270 bool has_debug_info = method_data.HasDebugInfo();
1271 size_t debug_info_idx = method_data.debug_info_idx;
1272
1273 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1274
1275 // Derived from CompiledMethod.
1276 uint32_t quick_code_offset = 0;
1277
1278 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1279 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1280 uint32_t thumb_offset = compiled_method->CodeDelta();
1281
1282 // Deduplicate code arrays if we are not producing debuggable code.
1283 bool deduped = true;
1284 if (debuggable_) {
1285 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1286 if (quick_code_offset != 0u) {
1287 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1288 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001289 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001290 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1291 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001292 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001293 } else {
1294 quick_code_offset = dedupe_map_.GetOrCreate(
1295 compiled_method,
1296 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1297 deduped = false;
1298 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1299 });
1300 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001301
Igor Murashkin545412b2017-08-17 15:26:54 -07001302 if (code_size != 0) {
1303 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1304 // TODO: Should this be a hard failure?
1305 LOG(WARNING) << "Multiple definitions of "
1306 << method_ref.dex_file->PrettyMethod(method_ref.index)
1307 << " offsets " << relative_patcher_->GetOffset(method_ref)
1308 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001309 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001310 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1311 }
1312 }
1313
1314 // Update quick method header.
1315 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1316 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1317 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1318 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1319 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1320 // to 0-offset and we need to adjust it by code_offset.
1321 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001322 CHECK(!compiled_method->GetQuickCode().empty());
1323 // If the code is compiled, we write the offset of the stack map relative
1324 // to the code.
1325 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001326 vmap_table_offset += code_offset;
1327 DCHECK_LT(vmap_table_offset, code_offset);
1328 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001329 if (method_info_offset != 0u) {
1330 method_info_offset += code_offset;
1331 DCHECK_LT(method_info_offset, code_offset);
1332 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001333 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1334 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1335 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1336 *method_header = OatQuickMethodHeader(vmap_table_offset,
1337 method_info_offset,
1338 frame_size_in_bytes,
1339 core_spill_mask,
1340 fp_spill_mask,
1341 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001342
Igor Murashkin545412b2017-08-17 15:26:54 -07001343 if (!deduped) {
1344 // Update offsets. (Checksum is updated when writing.)
1345 offset_ += sizeof(*method_header); // Method header is prepended before code.
1346 offset_ += code_size;
1347 // Record absolute patch locations.
1348 if (!compiled_method->GetPatches().empty()) {
1349 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1350 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1351 if (!patch.IsPcRelative()) {
1352 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001353 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001354 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001355 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001356 }
1357
Igor Murashkin545412b2017-08-17 15:26:54 -07001358 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1359 if (generate_debug_info_ && code_size != 0) {
1360 DCHECK(has_debug_info);
1361
1362 bool has_code_info = method_header->IsOptimized();
1363 // Record debug information for this function if we are doing that.
1364 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
David Srbeckyc684f332018-01-19 17:38:06 +00001365 DCHECK(info.custom_name.empty());
Igor Murashkin545412b2017-08-17 15:26:54 -07001366 info.dex_file = method_ref.dex_file;
1367 info.class_def_index = class_def_index;
1368 info.dex_method_index = method_ref.index;
1369 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001370 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1371 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001372 info.isa = compiled_method->GetInstructionSet();
1373 info.deduped = deduped;
1374 info.is_native_debuggable = native_debuggable_;
1375 info.is_optimized = method_header->IsOptimized();
1376 info.is_code_address_text_relative = true;
1377 info.code_address = code_offset - executable_offset_;
1378 info.code_size = code_size;
1379 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1380 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1381 info.cfi = compiled_method->GetCFIInfo();
1382 } else {
1383 DCHECK(!has_debug_info);
1384 }
1385
1386 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1387 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1388 offsets->code_offset_ = quick_code_offset;
1389
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001390 return true;
1391 }
1392
Igor Murashkin545412b2017-08-17 15:26:54 -07001393 size_t GetOffset() const {
1394 return offset_;
1395 }
1396
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001397 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001398 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1399 size_t offset,
1400 const CompilerOptions& compiler_options,
1401 OrderedMethodList ordered_methods)
1402 : OrderedMethodVisitor(std::move(ordered_methods)),
1403 writer_(writer),
1404 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001405 relative_patcher_(writer->relative_patcher_),
1406 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1407 debuggable_(compiler_options.GetDebuggable()),
1408 native_debuggable_(compiler_options.GetNativeDebuggable()),
1409 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1410 writer->absolute_patch_locations_.reserve(
1411 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1412 }
1413
Vladimir Marko20f85592015-03-19 10:07:02 +00001414 struct CodeOffsetsKeyComparator {
1415 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001416 // Code is deduplicated by CompilerDriver, compare only data pointers.
1417 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1418 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001419 }
1420 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001421 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1422 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001423 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001424 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1425 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1426 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001427 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1428 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001429 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001430 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1431 return rhs->IsIntrinsic();
1432 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001433 return false;
1434 }
1435 };
1436
David Srbecky009e2a62015-04-15 02:46:30 +01001437 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001438 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001439 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001440 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001441 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1442 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001443 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1444 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1445 }
1446
Igor Murashkin545412b2017-08-17 15:26:54 -07001447 OatWriter* writer_;
1448
1449 // Offset of the code of the compiled methods.
1450 size_t offset_;
1451
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001452 // Deduplication is already done on a pointer basis by the compiler driver,
1453 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001454 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001455
Vladimir Marko1b404a82017-09-01 13:35:26 +01001456 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001457 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001458 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001459 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001460 const bool native_debuggable_;
1461 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001462};
1463
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001464class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1465 public:
1466 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001467 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001469 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001470 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001471 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001472 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1473
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001474 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001475 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001476 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001477
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001478 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1479 uint32_t map_size = map.size() * sizeof(map[0]);
1480 if (map_size != 0u) {
1481 size_t offset = dedupe_map_.GetOrCreate(
1482 map.data(),
1483 [this, map_size]() {
1484 uint32_t new_offset = offset_;
1485 offset_ += map_size;
1486 return new_offset;
1487 });
1488 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1489 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1490 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001491 }
1492 ++method_offsets_index_;
1493 }
1494
1495 return true;
1496 }
1497
1498 private:
1499 // Deduplication is already done on a pointer basis by the compiler driver,
1500 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001501 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001502};
1503
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001504class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1505 public:
1506 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1507
1508 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001509 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001510 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1511 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1512
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001513 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001514 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1515 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1516 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1517 const uint32_t map_size = map.size() * sizeof(map[0]);
1518 if (map_size != 0u) {
1519 size_t offset = dedupe_map_.GetOrCreate(
1520 map.data(),
1521 [this, map_size]() {
1522 uint32_t new_offset = offset_;
1523 offset_ += map_size;
1524 return new_offset;
1525 });
1526 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1527 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1528 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1529 }
1530 ++method_offsets_index_;
1531 }
1532
1533 return true;
1534 }
1535
1536 private:
1537 // Deduplication is already done on a pointer basis by the compiler driver,
1538 // so we can simply compare the pointers to find out if things are duplicated.
1539 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1540};
1541
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001542class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1543 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001544 InitImageMethodVisitor(OatWriter* writer,
1545 size_t offset,
1546 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001547 : OatDexMethodVisitor(writer, offset),
Vladimir Markoa0431112018-06-25 09:32:54 +01001548 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001549 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001550 dex_files_(dex_files),
1551 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001552
1553 // Handle copied methods here. Copy pointer to quick code from
1554 // an origin method to a copied method only if they are
1555 // in the same oat file. If the origin and the copied methods are
1556 // in different oat files don't touch the copied method.
1557 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001558 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001559 REQUIRES_SHARED(Locks::mutator_lock_) {
1560 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1561 // Skip classes that are not in the image.
1562 if (!IsImageClass()) {
1563 return true;
1564 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001565 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001566 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1567 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1568 if (klass != nullptr) {
1569 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1570 // Find origin method. Declaring class and dex_method_idx
1571 // in the copied method should be the same as in the origin
1572 // method.
Vladimir Markoc945e0d2018-07-18 17:26:45 +01001573 ObjPtr<mirror::Class> declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001574 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001575 declaring_class->GetDexCache(),
1576 method.GetDexMethodIndex(),
1577 pointer_size_);
1578 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001579 CHECK(!origin->IsDirect());
1580 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001581 if (IsInOatFile(&declaring_class->GetDexFile())) {
1582 const void* code_ptr =
1583 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1584 if (code_ptr == nullptr) {
1585 methods_to_process_.push_back(std::make_pair(&method, origin));
1586 } else {
1587 method.SetEntryPointFromQuickCompiledCodePtrSize(
1588 code_ptr, pointer_size_);
1589 }
1590 }
1591 }
1592 }
1593 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001594 }
1595
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001596 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001597 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001598 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001599 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001600 return true;
1601 }
1602
Vladimir Marko49b0f452015-12-10 13:49:19 +00001603 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001604 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1605
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001606 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001607 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001608 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1609 offsets = oat_class->method_offsets_[method_offsets_index_];
1610 ++method_offsets_index_;
1611 }
1612
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001613 Thread* self = Thread::Current();
1614 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001615 ArtMethod* method;
Vladimir Markoa0431112018-06-25 09:32:54 +01001616 if (writer_->GetCompilerOptions().IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001617 const InvokeType invoke_type = it.GetMethodInvokeType(
1618 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001619 // Unchecked as we hold mutator_lock_ on entry.
1620 ScopedObjectAccessUnchecked soa(self);
1621 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001622 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001623 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001624 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001625 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Marko89011192017-12-11 13:45:05 +00001626 /* referrer */ nullptr,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001627 invoke_type);
1628 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001629 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001630 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001631 self->AssertPendingException();
1632 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001633 std::string dump = exc->Dump();
1634 LOG(FATAL) << dump;
1635 UNREACHABLE();
1636 }
1637 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001638 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001639 // 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 +01001640 // entrypoint. This is not fatal since we shall use a resolution method.
1641 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001642 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001643 if (method != nullptr &&
1644 compiled_method != nullptr &&
1645 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001646 method->SetEntryPointFromQuickCompiledCodePtrSize(
1647 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1648 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001649
1650 return true;
1651 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001652
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001653 // Check whether current class is image class
1654 bool IsImageClass() {
1655 const DexFile::TypeId& type_id =
1656 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1657 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001658 return writer_->GetCompilerOptions().IsImageClass(class_descriptor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001659 }
1660
1661 // Check whether specified dex file is in the compiled oat file.
1662 bool IsInOatFile(const DexFile* dex_file) {
1663 return ContainsElement(*dex_files_, dex_file);
1664 }
1665
1666 // Assign a pointer to quick code for copied methods
1667 // not handled in the method StartClass
1668 void Postprocess() {
1669 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1670 ArtMethod* method = p.first;
1671 ArtMethod* origin = p.second;
1672 const void* code_ptr =
1673 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1674 if (code_ptr != nullptr) {
1675 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1676 }
1677 }
1678 }
1679
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001680 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001681 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001682 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001683 const std::vector<const DexFile*>* dex_files_;
1684 ClassLinker* const class_linker_;
1685 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001686};
1687
Igor Murashkin545412b2017-08-17 15:26:54 -07001688class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001689 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001690 WriteCodeMethodVisitor(OatWriter* writer,
1691 OutputStream* out,
1692 const size_t file_offset,
1693 size_t relative_offset,
1694 OrderedMethodList ordered_methods)
1695 : OrderedMethodVisitor(std::move(ordered_methods)),
1696 writer_(writer),
1697 offset_(relative_offset),
1698 dex_file_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +01001699 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001700 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1701 out_(out),
1702 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001703 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001704 dex_cache_(nullptr),
1705 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001706 patched_code_.reserve(16 * KB);
Vladimir Markoa0431112018-06-25 09:32:54 +01001707 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001708 // If we're creating the image, the address space must be ready so that we can apply patches.
1709 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001710 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001711 }
1712
Igor Murashkin545412b2017-08-17 15:26:54 -07001713 virtual bool VisitStart() OVERRIDE {
1714 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001715 }
1716
Igor Murashkin545412b2017-08-17 15:26:54 -07001717 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001718 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001719 dex_file_ = dex_file;
1720
1721 // Ordered method visiting is only for compiled methods.
1722 DCHECK(writer_->MayHaveCompiledMethods());
1723
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001724 if (writer_->GetCompilerOptions().IsAotCompilationEnabled()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001725 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1726 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1727 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1728 DCHECK(dex_cache_ != nullptr);
1729 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001730 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001731 }
1732
1733 virtual bool VisitComplete() {
1734 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1735 if (UNLIKELY(offset_ == 0u)) {
1736 PLOG(ERROR) << "Failed to write final relative call thunks";
1737 return false;
1738 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001739 return true;
1740 }
1741
Igor Murashkin545412b2017-08-17 15:26:54 -07001742 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001743 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001744 const MethodReference& method_ref = method_data.method_reference;
1745 UpdateDexFileAndDexCache(method_ref.dex_file);
1746
1747 OatClass* oat_class = method_data.oat_class;
1748 CompiledMethod* compiled_method = method_data.compiled_method;
1749 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001750
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001751 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001752 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001753 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001754
Igor Murashkin545412b2017-08-17 15:26:54 -07001755 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1756 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1757 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001758
Igor Murashkin545412b2017-08-17 15:26:54 -07001759 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1760 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1761
1762 // Deduplicate code arrays.
1763 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1764 if (method_offsets.code_offset_ > offset_) {
1765 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1766 if (offset_ == 0u) {
1767 ReportWriteFailure("relative call thunk", method_ref);
1768 return false;
1769 }
1770 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1771 if (alignment_size != 0) {
1772 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1773 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001774 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001775 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001776 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001777 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001778 }
1779 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1780 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1781 DCHECK_EQ(method_offsets.code_offset_,
1782 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1783 << dex_file_->PrettyMethod(method_ref.index);
1784 const OatQuickMethodHeader& method_header =
1785 oat_class->method_headers_[method_offsets_index];
1786 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1787 ReportWriteFailure("method header", method_ref);
1788 return false;
1789 }
1790 writer_->size_method_header_ += sizeof(method_header);
1791 offset_ += sizeof(method_header);
1792 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001793
Igor Murashkin545412b2017-08-17 15:26:54 -07001794 if (!compiled_method->GetPatches().empty()) {
1795 patched_code_.assign(quick_code.begin(), quick_code.end());
1796 quick_code = ArrayRef<const uint8_t>(patched_code_);
1797 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1798 uint32_t literal_offset = patch.LiteralOffset();
1799 switch (patch.GetType()) {
Vladimir Marko6fd16062018-06-26 11:02:04 +01001800 case LinkerPatch::Type::kIntrinsicReference: {
1801 uint32_t target_offset = GetTargetIntrinsicReferenceOffset(patch);
1802 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1803 patch,
1804 offset_ + literal_offset,
1805 target_offset);
1806 break;
1807 }
Vladimir Markob066d432018-01-03 13:14:37 +00001808 case LinkerPatch::Type::kDataBimgRelRo: {
1809 uint32_t target_offset =
1810 writer_->data_bimg_rel_ro_start_ +
1811 writer_->data_bimg_rel_ro_entries_.Get(patch.BootImageOffset());
1812 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1813 patch,
1814 offset_ + literal_offset,
1815 target_offset);
1816 break;
1817 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001818 case LinkerPatch::Type::kMethodBssEntry: {
1819 uint32_t target_offset =
1820 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1821 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1822 patch,
1823 offset_ + literal_offset,
1824 target_offset);
1825 break;
1826 }
1827 case LinkerPatch::Type::kCallRelative: {
1828 // NOTE: Relative calls across oat files are not supported.
1829 uint32_t target_offset = GetTargetOffset(patch);
1830 writer_->relative_patcher_->PatchCall(&patched_code_,
1831 literal_offset,
1832 offset_ + literal_offset,
1833 target_offset);
1834 break;
1835 }
1836 case LinkerPatch::Type::kStringRelative: {
1837 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1838 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1839 patch,
1840 offset_ + literal_offset,
1841 target_offset);
1842 break;
1843 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001844 case LinkerPatch::Type::kStringBssEntry: {
1845 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1846 uint32_t target_offset =
1847 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1848 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1849 patch,
1850 offset_ + literal_offset,
1851 target_offset);
1852 break;
1853 }
1854 case LinkerPatch::Type::kTypeRelative: {
1855 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1856 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1857 patch,
1858 offset_ + literal_offset,
1859 target_offset);
1860 break;
1861 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001862 case LinkerPatch::Type::kTypeBssEntry: {
1863 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1864 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1865 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1866 patch,
1867 offset_ + literal_offset,
1868 target_offset);
1869 break;
1870 }
1871 case LinkerPatch::Type::kCall: {
1872 uint32_t target_offset = GetTargetOffset(patch);
1873 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1874 break;
1875 }
1876 case LinkerPatch::Type::kMethodRelative: {
1877 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1878 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1879 patch,
1880 offset_ + literal_offset,
1881 target_offset);
1882 break;
1883 }
1884 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1885 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1886 patch,
1887 offset_ + literal_offset);
1888 break;
1889 }
1890 default: {
1891 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1892 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001893 }
1894 }
1895 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001896 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001897
1898 if (!out->WriteFully(quick_code.data(), code_size)) {
1899 ReportWriteFailure("method code", method_ref);
1900 return false;
1901 }
1902 writer_->size_code_ += code_size;
1903 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001904 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001905 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001906
1907 return true;
1908 }
1909
Igor Murashkin545412b2017-08-17 15:26:54 -07001910 size_t GetOffset() const {
1911 return offset_;
1912 }
1913
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001914 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001915 OatWriter* const writer_;
1916
1917 // Updated in VisitMethod as methods are written out.
1918 size_t offset_;
1919
1920 // Potentially varies with every different VisitMethod.
1921 // Used to determine which DexCache to use when finding ArtMethods.
1922 const DexFile* dex_file_;
1923
1924 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001925 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001926 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001927 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001928 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001929 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001930 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001931 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001932 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001933 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001934 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001935
Igor Murashkin545412b2017-08-17 15:26:54 -07001936 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001937 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001938 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001939 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001940
Mathieu Chartiere401d142015-04-22 13:56:20 -07001941 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001942 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001943 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001944 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001945 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1946 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001947 ArtMethod* method =
1948 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001949 CHECK(method != nullptr);
1950 return method;
1951 }
1952
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001953 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001954 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1955 // If there's no new compiled code, either we're compiling an app and the target method
1956 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001957 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001958 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001959 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001960 const void* oat_code_offset =
1961 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001962 if (oat_code_offset != 0) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001963 DCHECK(!writer_->GetCompilerOptions().IsBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001964 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1965 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1966 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1967 target_offset = PointerToLowMemUInt32(oat_code_offset);
1968 } else {
1969 target_offset = target->IsNative()
1970 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1971 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1972 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001973 }
1974 return target_offset;
1975 }
1976
Vladimir Markocd556b02017-02-03 11:47:34 +00001977 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001978 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001979 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001980 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001981 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1982 }
1983
Vladimir Marko28e012a2017-12-07 11:22:59 +00001984 ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1985 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001986 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001987 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001988 ObjPtr<mirror::Class> type =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001989 class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001990 CHECK(type != nullptr);
Vladimir Marko28e012a2017-12-07 11:22:59 +00001991 return type;
Vladimir Markof4da6752014-08-01 19:04:18 +01001992 }
1993
Vladimir Marko28e012a2017-12-07 11:22:59 +00001994 ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1995 REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001996 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Markoa64b52d2017-12-08 16:27:49 +00001997 ObjPtr<mirror::String> string =
1998 linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001999 DCHECK(string != nullptr);
Vladimir Markoa0431112018-06-25 09:32:54 +01002000 DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002001 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
2002 return string;
2003 }
2004
Vladimir Marko6fd16062018-06-26 11:02:04 +01002005 uint32_t GetTargetIntrinsicReferenceOffset(const LinkerPatch& patch)
2006 REQUIRES_SHARED(Locks::mutator_lock_) {
2007 DCHECK(writer_->GetCompilerOptions().IsBootImage());
2008 const void* address =
2009 writer_->image_writer_->GetIntrinsicReferenceAddress(patch.IntrinsicData());
2010 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
2011 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
2012 // TODO: Clean up offset types. The target offset must be treated as signed.
2013 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(address) - oat_data_begin);
2014 }
2015
Vladimir Marko65979462017-05-19 17:25:12 +01002016 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002017 DCHECK(writer_->GetCompilerOptions().IsBootImage());
Vladimir Marko65979462017-05-19 17:25:12 +01002018 method = writer_->image_writer_->GetImageMethodAddress(method);
2019 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
2020 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
2021 // TODO: Clean up offset types. The target offset must be treated as signed.
2022 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
2023 }
2024
Vladimir Marko28e012a2017-12-07 11:22:59 +00002025 uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
2026 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002027 DCHECK(writer_->GetCompilerOptions().IsBootImage());
Vladimir Marko28e012a2017-12-07 11:22:59 +00002028 object = writer_->image_writer_->GetImageAddress(object.Ptr());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002029 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
2030 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
2031 // TODO: Clean up offset types. The target offset must be treated as signed.
Vladimir Marko28e012a2017-12-07 11:22:59 +00002032 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002033 }
2034
Vladimir Markof4da6752014-08-01 19:04:18 +01002035 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002036 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002037 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002038 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01002039 } else {
2040 // NOTE: We're using linker patches for app->boot references when the image can
2041 // be relocated and therefore we need to emit .oat_patches. We're not using this
2042 // for app->app references, so check that the object is in the image space.
2043 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01002044 }
Vladimir Marko09d09432015-09-08 13:47:48 +01002045 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01002046 uint32_t address = PointerToLowMemUInt32(object);
2047 DCHECK_LE(offset + 4, code->size());
2048 uint8_t* data = &(*code)[offset];
2049 data[0] = address & 0xffu;
2050 data[1] = (address >> 8) & 0xffu;
2051 data[2] = (address >> 16) & 0xffu;
2052 data[3] = (address >> 24) & 0xffu;
2053 }
2054
2055 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002056 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01002057 uint32_t address = target_offset;
Vladimir Markoa0431112018-06-25 09:32:54 +01002058 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002059 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
2060 // TODO: Clean up offset types.
2061 // The target_offset must be treated as signed for cross-oat patching.
2062 const void* target = reinterpret_cast<const void*>(
2063 writer_->image_writer_->GetOatDataBegin(oat_index) +
2064 static_cast<int32_t>(target_offset));
2065 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01002066 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002067 DCHECK_LE(offset + 4, code->size());
2068 uint8_t* data = &(*code)[offset];
2069 data[0] = address & 0xffu;
2070 data[1] = (address >> 8) & 0xffu;
2071 data[2] = (address >> 16) & 0xffu;
2072 data[3] = (address >> 24) & 0xffu;
2073 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002074};
2075
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002076class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2077 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002078 WriteMapMethodVisitor(OatWriter* writer,
2079 OutputStream* out,
2080 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002081 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002082 : OatDexMethodVisitor(writer, relative_offset),
2083 out_(out),
2084 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002085
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002086 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002087 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002088 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2089
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002090 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002091 size_t file_offset = file_offset_;
2092 OutputStream* out = out_;
2093
Mingyao Yang063fc772016-08-02 11:02:54 -07002094 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002095 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002096 ++method_offsets_index_;
2097
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002098 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2099 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2100 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002101 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002102
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002103 // If vdex is enabled, only emit the map for compiled code. The quickening info
2104 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002105 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002106 // Transform map_offset to actual oat data offset.
2107 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2108 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002109 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002110
2111 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2112 size_t map_size = map.size() * sizeof(map[0]);
2113 if (map_offset == offset_) {
2114 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002115 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002116 ReportWriteFailure(it);
2117 return false;
2118 }
2119 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002120 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002121 }
2122 DCHECK_OFFSET_();
2123 }
2124
2125 return true;
2126 }
2127
2128 private:
2129 OutputStream* const out_;
2130 size_t const file_offset_;
2131
2132 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002133 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002134 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002135 }
2136};
2137
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002138class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2139 public:
2140 WriteMethodInfoVisitor(OatWriter* writer,
2141 OutputStream* out,
2142 const size_t file_offset,
2143 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002144 : OatDexMethodVisitor(writer, relative_offset),
2145 out_(out),
2146 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002147
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002148 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002149 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2150 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2151
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002152 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002153 size_t file_offset = file_offset_;
2154 OutputStream* out = out_;
2155 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2156 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2157 ++method_offsets_index_;
2158 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2159 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2160 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2161 << dex_file_->PrettyMethod(it.GetMemberIndex());
2162 if (map_offset != 0u) {
2163 // Transform map_offset to actual oat data offset.
2164 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2165 DCHECK_NE(map_offset, 0u);
2166 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2167
2168 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2169 size_t map_size = map.size() * sizeof(map[0]);
2170 if (map_offset == offset_) {
2171 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2172 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2173 ReportWriteFailure(it);
2174 return false;
2175 }
2176 offset_ += map_size;
2177 }
2178 }
2179 DCHECK_OFFSET_();
2180 }
2181
2182 return true;
2183 }
2184
2185 private:
2186 OutputStream* const out_;
2187 size_t const file_offset_;
2188
2189 void ReportWriteFailure(const ClassDataItemIterator& it) {
2190 PLOG(ERROR) << "Failed to write map for "
2191 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2192 }
2193};
2194
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002195// Visit all methods from all classes in all dex files with the specified visitor.
2196bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2197 for (const DexFile* dex_file : *dex_files_) {
2198 const size_t class_def_count = dex_file->NumClassDefs();
2199 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2200 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2201 return false;
2202 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002203 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002204 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2205 const uint8_t* class_data = dex_file->GetClassData(class_def);
2206 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2207 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002208 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002209 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002210 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002211 if (!visitor->VisitMethod(class_def_method_index, it)) {
2212 return false;
2213 }
2214 ++class_def_method_index;
2215 it.Next();
2216 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002217 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002218 }
2219 }
2220 if (UNLIKELY(!visitor->EndClass())) {
2221 return false;
2222 }
2223 }
2224 }
2225 return true;
2226}
2227
Vladimir Markoa0431112018-06-25 09:32:54 +01002228size_t OatWriter::InitOatHeader(uint32_t num_dex_files,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002229 SafeMap<std::string, std::string>* key_value_store) {
2230 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
Vladimir Markoa0431112018-06-25 09:32:54 +01002231 oat_header_.reset(OatHeader::Create(GetCompilerOptions().GetInstructionSet(),
2232 GetCompilerOptions().GetInstructionSetFeatures(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002233 num_dex_files,
2234 key_value_store));
2235 size_oat_header_ += sizeof(OatHeader);
2236 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002237 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002238}
2239
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002240size_t OatWriter::InitClassOffsets(size_t offset) {
2241 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002242 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002243 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2244 if (!oat_dex_file.class_offsets_.empty()) {
2245 // Class offsets are required to be 4 byte aligned.
2246 offset = RoundUp(offset, 4u);
2247 oat_dex_file.class_offsets_offset_ = offset;
2248 offset += oat_dex_file.GetClassOffsetsRawSize();
2249 DCHECK_ALIGNED(offset, 4u);
2250 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002251 }
2252 return offset;
2253}
2254
Brian Carlstrom389efb02012-01-11 12:06:26 -08002255size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002256 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002257 InitOatClassesMethodVisitor visitor(this, offset);
2258 bool success = VisitDexMethods(&visitor);
2259 CHECK(success);
2260 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002261
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002262 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002263 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002264 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2265 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002266 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002267 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002268 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002269 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002270 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002271 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002272
2273 return offset;
2274}
2275
2276size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002277 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002278 return offset;
2279 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002280 {
2281 InitMapMethodVisitor visitor(this, offset);
2282 bool success = VisitDexMethods(&visitor);
2283 DCHECK(success);
2284 offset = visitor.GetOffset();
2285 }
2286 {
2287 InitMethodInfoVisitor visitor(this, offset);
2288 bool success = VisitDexMethods(&visitor);
2289 DCHECK(success);
2290 offset = visitor.GetOffset();
2291 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002292 return offset;
2293}
2294
Vladimir Markof3c52b42017-11-17 17:32:12 +00002295template <typename GetBssOffset>
2296static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2297 size_t slot_size,
2298 const BitVector& indexes,
2299 GetBssOffset get_bss_offset) {
2300 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2301 size_t number_of_entries = 0u;
2302 bool first_index = true;
2303 for (uint32_t index : indexes.Indexes()) {
2304 uint32_t bss_offset = get_bss_offset(index);
2305 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2306 encoder.Reset(index, bss_offset);
2307 ++number_of_entries;
2308 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002309 }
2310 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002311 DCHECK_NE(number_of_entries, 0u);
2312 return number_of_entries;
2313}
2314
2315template <typename GetBssOffset>
2316static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2317 size_t slot_size,
2318 const BitVector& indexes,
2319 GetBssOffset get_bss_offset) {
2320 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2321 slot_size,
2322 indexes,
2323 get_bss_offset);
2324 return IndexBssMapping::ComputeSize(number_of_entries);
2325}
2326
2327size_t OatWriter::InitIndexBssMappings(size_t offset) {
2328 if (bss_method_entry_references_.empty() &&
2329 bss_type_entry_references_.empty() &&
2330 bss_string_entry_references_.empty()) {
2331 return offset;
2332 }
2333 // If there are any classes, the class offsets allocation aligns the offset
2334 // and we cannot have any index bss mappings without class offsets.
2335 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2336 DCHECK_ALIGNED(offset, 4u);
2337
2338 size_t number_of_method_dex_files = 0u;
2339 size_t number_of_type_dex_files = 0u;
2340 size_t number_of_string_dex_files = 0u;
2341 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2342 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2343 const DexFile* dex_file = (*dex_files_)[i];
2344 auto method_it = bss_method_entry_references_.find(dex_file);
2345 if (method_it != bss_method_entry_references_.end()) {
2346 const BitVector& method_indexes = method_it->second;
2347 ++number_of_method_dex_files;
2348 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2349 offset += CalculateIndexBssMappingSize(
2350 dex_file->NumMethodIds(),
2351 static_cast<size_t>(pointer_size),
2352 method_indexes,
2353 [=](uint32_t index) {
2354 return bss_method_entries_.Get({dex_file, index});
2355 });
2356 }
2357
2358 auto type_it = bss_type_entry_references_.find(dex_file);
2359 if (type_it != bss_type_entry_references_.end()) {
2360 const BitVector& type_indexes = type_it->second;
2361 ++number_of_type_dex_files;
2362 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2363 offset += CalculateIndexBssMappingSize(
2364 dex_file->NumTypeIds(),
2365 sizeof(GcRoot<mirror::Class>),
2366 type_indexes,
2367 [=](uint32_t index) {
2368 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2369 });
2370 }
2371
2372 auto string_it = bss_string_entry_references_.find(dex_file);
2373 if (string_it != bss_string_entry_references_.end()) {
2374 const BitVector& string_indexes = string_it->second;
2375 ++number_of_string_dex_files;
2376 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2377 offset += CalculateIndexBssMappingSize(
2378 dex_file->NumStringIds(),
2379 sizeof(GcRoot<mirror::String>),
2380 string_indexes,
2381 [=](uint32_t index) {
2382 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2383 });
2384 }
2385 }
2386 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2387 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2388 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2389 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002390 return offset;
2391}
2392
2393size_t OatWriter::InitOatDexFiles(size_t offset) {
2394 // Initialize offsets of oat dex files.
2395 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2396 oat_dex_file.offset_ = offset;
2397 offset += oat_dex_file.SizeOf();
2398 }
2399 return offset;
2400}
2401
Brian Carlstrome24fa612011-09-29 00:53:55 -07002402size_t OatWriter::InitOatCode(size_t offset) {
2403 // calculate the offsets within OatHeader to executable code
2404 size_t old_offset = offset;
2405 // required to be on a new page boundary
2406 offset = RoundUp(offset, kPageSize);
2407 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002408 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002409 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2410 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2411 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002412 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002413 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002414 const bool generate_debug_info = GetCompilerOptions().GenerateAnyDebugInfo();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002415 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002416
Vladimir Marko1b404a82017-09-01 13:35:26 +01002417 #define DO_TRAMPOLINE(field, fn_name) \
2418 offset = CompiledCode::AlignCode(offset, instruction_set); \
2419 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2420 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2421 (field) = compiler_driver_->Create ## fn_name(); \
2422 if (generate_debug_info) { \
2423 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +00002424 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +01002425 info.isa = instruction_set; \
2426 info.is_code_address_text_relative = true; \
2427 /* Use the code offset rather than the `adjusted_offset`. */ \
2428 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2429 info.code_size = (field)->size(); \
2430 method_info_.push_back(std::move(info)); \
2431 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002432 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002433
Ian Rogers848871b2013-08-05 10:56:33 -07002434 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002435 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002436 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002437 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2438 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002439
Ian Rogers848871b2013-08-05 10:56:33 -07002440 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002441 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002442 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002443 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002444 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002445 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002446 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002447 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002448 return offset;
2449}
2450
2451size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002452 if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002453 if (kOatWriterDebugOatCodeLayout) {
2454 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2455 << this << "), "
2456 << "compilation is disabled";
2457 }
2458
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002459 return offset;
2460 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002461 bool success = false;
2462
2463 {
2464 ScopedObjectAccess soa(Thread::Current());
2465
2466 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2467 success = VisitDexMethods(&layout_code_visitor);
2468 DCHECK(success);
2469
2470 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2471 this,
2472 offset,
2473 layout_code_visitor.ReleaseOrderedMethods());
2474 success = layout_reserve_code_visitor.Visit();
2475 DCHECK(success);
2476 offset = layout_reserve_code_visitor.GetOffset();
2477
2478 // Save the method order because the WriteCodeMethodVisitor will need this
2479 // order again.
2480 DCHECK(ordered_methods_ == nullptr);
2481 ordered_methods_.reset(
2482 new OrderedMethodList(
2483 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2484
2485 if (kOatWriterDebugOatCodeLayout) {
2486 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2487 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2488 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2489 LOG(INFO) << pretty_name
2490 << "@ offset "
2491 << relative_patcher_->GetOffset(ordered_method.method_reference)
2492 << " X hotness "
2493 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2494 }
2495 }
2496 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002497
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002498 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002499 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002500 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002501 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002502 DCHECK(success);
2503 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002504 }
Logan Chien8b977d32012-02-21 19:14:55 +08002505
Brian Carlstrome24fa612011-09-29 00:53:55 -07002506 return offset;
2507}
2508
Vladimir Markob066d432018-01-03 13:14:37 +00002509size_t OatWriter::InitDataBimgRelRoLayout(size_t offset) {
2510 DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
2511 if (data_bimg_rel_ro_entries_.empty()) {
2512 // Nothing to put to the .data.bimg.rel.ro section.
2513 return offset;
2514 }
2515
2516 data_bimg_rel_ro_start_ = RoundUp(offset, kPageSize);
2517
2518 for (auto& entry : data_bimg_rel_ro_entries_) {
2519 size_t& entry_offset = entry.second;
2520 entry_offset = data_bimg_rel_ro_size_;
2521 data_bimg_rel_ro_size_ += sizeof(uint32_t);
2522 }
2523
2524 offset = data_bimg_rel_ro_start_ + data_bimg_rel_ro_size_;
2525 return offset;
2526}
2527
Vladimir Markoaad75c62016-10-03 08:46:48 +00002528void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002529 {
2530 InitBssLayoutMethodVisitor visitor(this);
2531 bool success = VisitDexMethods(&visitor);
2532 DCHECK(success);
2533 }
2534
2535 DCHECK_EQ(bss_size_, 0u);
Vladimir Markoa0431112018-06-25 09:32:54 +01002536 if (GetCompilerOptions().IsBootImage()) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002537 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002538 }
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002539 if (bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002540 bss_type_entries_.empty() &&
2541 bss_string_entries_.empty()) {
2542 // Nothing to put to the .bss section.
2543 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002544 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002545
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002546 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002547 bss_methods_offset_ = bss_size_;
2548
2549 // Prepare offsets for .bss ArtMethod entries.
2550 for (auto& entry : bss_method_entries_) {
2551 DCHECK_EQ(entry.second, 0u);
2552 entry.second = bss_size_;
2553 bss_size_ += static_cast<size_t>(pointer_size);
2554 }
2555
Vladimir Markoaad75c62016-10-03 08:46:48 +00002556 bss_roots_offset_ = bss_size_;
2557
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002558 // Prepare offsets for .bss Class entries.
2559 for (auto& entry : bss_type_entries_) {
2560 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002561 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002562 bss_size_ += sizeof(GcRoot<mirror::Class>);
2563 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002564 // Prepare offsets for .bss String entries.
2565 for (auto& entry : bss_string_entries_) {
2566 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002567 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002568 bss_size_ += sizeof(GcRoot<mirror::String>);
2569 }
2570}
2571
David Srbeckybc90fd02015-04-22 19:40:27 +01002572bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002573 CHECK(write_state_ == WriteState::kWriteRoData);
2574
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002575 size_t file_offset = oat_data_offset_;
2576 off_t current_offset = out->Seek(0, kSeekCurrent);
2577 if (current_offset == static_cast<off_t>(-1)) {
2578 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2579 }
2580 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2581 size_t relative_offset = current_offset - file_offset;
2582
Vladimir Markoe079e212016-05-25 12:49:49 +01002583 // Wrap out to update checksum with each write.
2584 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2585 out = &checksum_updating_out;
2586
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002587 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2588 if (relative_offset == 0) {
2589 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002590 return false;
2591 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002592
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002593 relative_offset = WriteClasses(out, file_offset, relative_offset);
2594 if (relative_offset == 0) {
2595 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002596 return false;
2597 }
2598
Vladimir Markof3c52b42017-11-17 17:32:12 +00002599 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002600 if (relative_offset == 0) {
2601 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002602 return false;
2603 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002604
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002605 relative_offset = WriteMaps(out, file_offset, relative_offset);
2606 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002607 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2608 return false;
2609 }
2610
2611 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2612 if (relative_offset == 0) {
2613 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002614 return false;
2615 }
2616
David Srbeckybc90fd02015-04-22 19:40:27 +01002617 // Write padding.
2618 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2619 relative_offset += size_executable_offset_alignment_;
2620 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2621 size_t expected_file_offset = file_offset + relative_offset;
2622 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2623 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2624 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2625 return 0;
2626 }
2627 DCHECK_OFFSET();
2628
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002629 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002630 return true;
2631}
2632
Mathieu Chartier210531f2018-01-12 10:15:51 -08002633class OatWriter::WriteQuickeningInfoMethodVisitor {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002634 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002635 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out)
2636 : writer_(writer),
2637 out_(out) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002638
Mathieu Chartier210531f2018-01-12 10:15:51 -08002639 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002640 // Map of offsets for quicken info related to method indices.
2641 SafeMap<const uint8_t*, uint32_t> offset_map;
2642 // Use method index order to minimize the encoded size of the offset table.
Mathieu Chartier210531f2018-01-12 10:15:51 -08002643 for (const DexFile* dex_file : dex_files) {
2644 std::vector<uint32_t>* const offsets =
2645 &quicken_info_offset_indices_.Put(dex_file, std::vector<uint32_t>())->second;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002646 for (uint32_t method_idx = 0; method_idx < dex_file->NumMethodIds(); ++method_idx) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002647 uint32_t offset = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002648 MethodReference method_ref(dex_file, method_idx);
2649 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(method_ref);
2650 if (compiled_method != nullptr && HasQuickeningInfo(compiled_method)) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002651 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Mathieu Chartier210531f2018-01-12 10:15:51 -08002652
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002653 // Record each index if required. written_bytes_ is the offset from the start of the
2654 // quicken info data.
2655 // May be already inserted for deduplicate items.
2656 // Add offset of one to make sure 0 represents unused.
2657 auto pair = offset_map.emplace(map.data(), written_bytes_ + 1);
2658 offset = pair.first->second;
2659 // Write out the map if it's not already written.
2660 if (pair.second) {
2661 const uint32_t length = map.size() * sizeof(map.front());
2662 if (!out_->WriteFully(map.data(), length)) {
2663 PLOG(ERROR) << "Failed to write quickening info for " << method_ref.PrettyMethod()
2664 << " to " << out_->GetLocation();
2665 return false;
2666 }
2667 written_bytes_ += length;
2668 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002669 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002670 offsets->push_back(offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002671 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002672 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002673 return true;
2674 }
2675
2676 size_t GetNumberOfWrittenBytes() const {
2677 return written_bytes_;
2678 }
2679
Mathieu Chartier210531f2018-01-12 10:15:51 -08002680 SafeMap<const DexFile*, std::vector<uint32_t>>& GetQuickenInfoOffsetIndicies() {
2681 return quicken_info_offset_indices_;
2682 }
2683
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002684 private:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002685 OatWriter* const writer_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002686 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002687 size_t written_bytes_ = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002688 SafeMap<const DexFile*, std::vector<uint32_t>> quicken_info_offset_indices_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002689};
2690
Mathieu Chartier210531f2018-01-12 10:15:51 -08002691class OatWriter::WriteQuickeningInfoOffsetsMethodVisitor {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002692 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002693 WriteQuickeningInfoOffsetsMethodVisitor(
2694 OutputStream* out,
2695 uint32_t start_offset,
2696 SafeMap<const DexFile*, std::vector<uint32_t>>* quicken_info_offset_indices,
2697 std::vector<uint32_t>* out_table_offsets)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002698 : out_(out),
Mathieu Chartier210531f2018-01-12 10:15:51 -08002699 start_offset_(start_offset),
2700 quicken_info_offset_indices_(quicken_info_offset_indices),
2701 out_table_offsets_(out_table_offsets) {}
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002702
Mathieu Chartier210531f2018-01-12 10:15:51 -08002703 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002704 for (const DexFile* dex_file : dex_files) {
Mathieu Chartier210531f2018-01-12 10:15:51 -08002705 auto it = quicken_info_offset_indices_->find(dex_file);
2706 DCHECK(it != quicken_info_offset_indices_->end()) << "Failed to find dex file "
2707 << dex_file->GetLocation();
2708 const std::vector<uint32_t>* const offsets = &it->second;
2709
2710 const uint32_t current_offset = start_offset_ + written_bytes_;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002711 CHECK_ALIGNED_PARAM(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002712
2713 // Generate and write the data.
2714 std::vector<uint8_t> table_data;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002715 CompactOffsetTable::Build(*offsets, &table_data);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002716
2717 // Store the offset since we need to put those after the dex file. Table offsets are relative
2718 // to the start of the quicken info section.
2719 out_table_offsets_->push_back(current_offset);
2720
2721 const uint32_t length = table_data.size() * sizeof(table_data.front());
2722 if (!out_->WriteFully(table_data.data(), length)) {
2723 PLOG(ERROR) << "Failed to write quickening offset table for " << dex_file->GetLocation()
2724 << " to " << out_->GetLocation();
2725 return false;
2726 }
2727 written_bytes_ += length;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002728 }
2729 return true;
2730 }
2731
2732 size_t GetNumberOfWrittenBytes() const {
2733 return written_bytes_;
2734 }
2735
2736 private:
2737 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002738 const uint32_t start_offset_;
2739 size_t written_bytes_ = 0u;
2740 // Maps containing the offsets for the tables.
2741 SafeMap<const DexFile*, std::vector<uint32_t>>* const quicken_info_offset_indices_;
2742 std::vector<uint32_t>* const out_table_offsets_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002743};
2744
2745bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08002746 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002747 // Nothing to write. Leave `vdex_size_` untouched and unaligned.
2748 vdex_quickening_info_offset_ = vdex_size_;
2749 size_quickening_info_alignment_ = 0;
2750 return true;
2751 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002752 size_t initial_offset = vdex_size_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002753 // Make sure the table is properly aligned.
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002754 size_t start_offset = RoundUp(initial_offset, 4u);
2755
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002756 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2757 if (actual_offset != static_cast<off_t>(start_offset)) {
2758 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2759 << " Expected: " << start_offset
2760 << " Output: " << vdex_out->GetLocation();
2761 return false;
2762 }
2763
Mathieu Chartier210531f2018-01-12 10:15:51 -08002764 size_t current_offset = start_offset;
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002765 if (GetCompilerOptions().IsQuickeningCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002766 std::vector<uint32_t> dex_files_indices;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002767 WriteQuickeningInfoMethodVisitor write_quicken_info_visitor(this, vdex_out);
2768 if (!write_quicken_info_visitor.VisitDexMethods(*dex_files_)) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002769 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2770 return false;
2771 }
2772
Mathieu Chartier210531f2018-01-12 10:15:51 -08002773 uint32_t quicken_info_offset = write_quicken_info_visitor.GetNumberOfWrittenBytes();
2774 current_offset = current_offset + quicken_info_offset;
2775 uint32_t before_offset = current_offset;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002776 current_offset = RoundUp(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002777 const size_t extra_bytes = current_offset - before_offset;
2778 quicken_info_offset += extra_bytes;
2779 actual_offset = vdex_out->Seek(current_offset, kSeekSet);
2780 if (actual_offset != static_cast<off_t>(current_offset)) {
2781 PLOG(ERROR) << "Failed to seek to quickening offset table section. Actual: " << actual_offset
2782 << " Expected: " << current_offset
2783 << " Output: " << vdex_out->GetLocation();
2784 return false;
2785 }
2786
2787 std::vector<uint32_t> table_offsets;
2788 WriteQuickeningInfoOffsetsMethodVisitor table_visitor(
2789 vdex_out,
2790 quicken_info_offset,
2791 &write_quicken_info_visitor.GetQuickenInfoOffsetIndicies(),
2792 /*out*/ &table_offsets);
2793 if (!table_visitor.VisitDexMethods(*dex_files_)) {
2794 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2795 << vdex_out->GetLocation();
2796 return false;
2797 }
2798
2799 CHECK_EQ(table_offsets.size(), dex_files_->size());
2800
2801 current_offset += table_visitor.GetNumberOfWrittenBytes();
2802
2803 // Store the offset table offset as a preheader for each dex.
2804 size_t index = 0;
2805 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
2806 const off_t desired_offset = oat_dex_file.dex_file_offset_ -
2807 sizeof(VdexFile::QuickeningTableOffsetType);
2808 actual_offset = vdex_out->Seek(desired_offset, kSeekSet);
2809 if (actual_offset != desired_offset) {
2810 PLOG(ERROR) << "Failed to seek to before dex file for writing offset table offset: "
2811 << actual_offset << " Expected: " << desired_offset
2812 << " Output: " << vdex_out->GetLocation();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002813 return false;
2814 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002815 uint32_t offset = table_offsets[index];
2816 if (!vdex_out->WriteFully(reinterpret_cast<const uint8_t*>(&offset), sizeof(offset))) {
2817 PLOG(ERROR) << "Failed to write verifier deps."
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002818 << " File: " << vdex_out->GetLocation();
2819 return false;
2820 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002821 ++index;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002822 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002823 if (!vdex_out->Flush()) {
2824 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2825 << " File: " << vdex_out->GetLocation();
2826 return false;
2827 }
2828 size_quickening_info_ = current_offset - start_offset;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002829 } else {
2830 // We know we did not quicken.
2831 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002832 }
2833
David Brazdil93592f52017-12-08 10:53:27 +00002834 if (size_quickening_info_ == 0) {
2835 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2836 vdex_quickening_info_offset_ = initial_offset;
2837 size_quickening_info_alignment_ = 0;
2838 } else {
2839 vdex_size_ = start_offset + size_quickening_info_;
2840 vdex_quickening_info_offset_ = start_offset;
2841 size_quickening_info_alignment_ = start_offset - initial_offset;
2842 }
2843
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002844 return true;
2845}
2846
David Brazdil5d5a36b2016-09-14 15:34:10 +01002847bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002848 if (verifier_deps == nullptr) {
2849 // Nothing to write. Record the offset, but no need
2850 // for alignment.
2851 vdex_verifier_deps_offset_ = vdex_size_;
2852 return true;
2853 }
2854
2855 size_t initial_offset = vdex_size_;
2856 size_t start_offset = RoundUp(initial_offset, 4u);
2857
2858 vdex_size_ = start_offset;
2859 vdex_verifier_deps_offset_ = vdex_size_;
2860 size_verifier_deps_alignment_ = start_offset - initial_offset;
2861
2862 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2863 if (actual_offset != static_cast<off_t>(start_offset)) {
2864 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2865 << " Expected: " << start_offset
2866 << " Output: " << vdex_out->GetLocation();
2867 return false;
2868 }
2869
2870 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002871 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002872
2873 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2874 PLOG(ERROR) << "Failed to write verifier deps."
2875 << " File: " << vdex_out->GetLocation();
2876 return false;
2877 }
2878 if (!vdex_out->Flush()) {
2879 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2880 << " File: " << vdex_out->GetLocation();
2881 return false;
2882 }
2883
2884 size_verifier_deps_ = buffer.size();
2885 vdex_size_ += size_verifier_deps_;
2886 return true;
2887}
2888
David Srbeckybc90fd02015-04-22 19:40:27 +01002889bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002890 CHECK(write_state_ == WriteState::kWriteText);
2891
Vladimir Markoe079e212016-05-25 12:49:49 +01002892 // Wrap out to update checksum with each write.
2893 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2894 out = &checksum_updating_out;
2895
Vladimir Marko944da602016-02-19 12:27:55 +00002896 SetMultiOatRelativePatcherAdjustment();
2897
David Srbeckybc90fd02015-04-22 19:40:27 +01002898 const size_t file_offset = oat_data_offset_;
2899 size_t relative_offset = oat_header_->GetExecutableOffset();
2900 DCHECK_OFFSET();
2901
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002902 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002903 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002904 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002905 return false;
2906 }
2907
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002908 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2909 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002910 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002911 return false;
2912 }
2913
Vladimir Markob066d432018-01-03 13:14:37 +00002914 if (data_bimg_rel_ro_size_ != 0u) {
2915 write_state_ = WriteState::kWriteDataBimgRelRo;
2916 } else {
2917 if (!CheckOatSize(out, file_offset, relative_offset)) {
2918 return false;
2919 }
2920 write_state_ = WriteState::kWriteHeader;
2921 }
2922 return true;
2923}
2924
2925bool OatWriter::WriteDataBimgRelRo(OutputStream* out) {
2926 CHECK(write_state_ == WriteState::kWriteDataBimgRelRo);
2927
2928 // Wrap out to update checksum with each write.
2929 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2930 out = &checksum_updating_out;
2931
2932 const size_t file_offset = oat_data_offset_;
2933 size_t relative_offset = data_bimg_rel_ro_start_;
2934
2935 // Record the padding before the .data.bimg.rel.ro section.
2936 // Do not write anything, this zero-filled part was skipped (Seek()) when starting the section.
2937 size_t code_end = GetOatHeader().GetExecutableOffset() + code_size_;
2938 DCHECK_EQ(RoundUp(code_end, kPageSize), relative_offset);
2939 size_t padding_size = relative_offset - code_end;
2940 DCHECK_EQ(size_data_bimg_rel_ro_alignment_, 0u);
2941 size_data_bimg_rel_ro_alignment_ = padding_size;
2942
2943 relative_offset = WriteDataBimgRelRo(out, file_offset, relative_offset);
2944 if (relative_offset == 0) {
2945 LOG(ERROR) << "Failed to write boot image relocations to " << out->GetLocation();
2946 return false;
2947 }
2948
2949 if (!CheckOatSize(out, file_offset, relative_offset)) {
2950 return false;
2951 }
2952 write_state_ = WriteState::kWriteHeader;
2953 return true;
2954}
2955
2956bool OatWriter::CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002957 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002958 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002959 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2960 return false;
2961 }
2962
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002963 if (kIsDebugBuild) {
2964 uint32_t size_total = 0;
2965 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002966 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2967 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002968
David Brazdil7b49e6c2016-09-01 11:06:18 +01002969 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002970 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002971 DO_STAT(size_dex_file_alignment_);
2972 DO_STAT(size_executable_offset_alignment_);
2973 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002974 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002975 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002976 DO_STAT(size_verifier_deps_);
2977 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002978 DO_STAT(size_quickening_info_);
2979 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002980 DO_STAT(size_interpreter_to_interpreter_bridge_);
2981 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2982 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002983 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002984 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002985 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002986 DO_STAT(size_quick_to_interpreter_bridge_);
2987 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002988 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002989 DO_STAT(size_code_);
2990 DO_STAT(size_code_alignment_);
Vladimir Markob066d432018-01-03 13:14:37 +00002991 DO_STAT(size_data_bimg_rel_ro_);
2992 DO_STAT(size_data_bimg_rel_ro_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002993 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002994 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002995 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002996 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002997 DO_STAT(size_oat_dex_file_location_size_);
2998 DO_STAT(size_oat_dex_file_location_data_);
2999 DO_STAT(size_oat_dex_file_location_checksum_);
3000 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003001 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003002 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07003003 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
3004 DO_STAT(size_oat_dex_file_dex_layout_sections_);
3005 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003006 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00003007 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
3008 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00003009 DO_STAT(size_oat_lookup_table_alignment_);
3010 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003011 DO_STAT(size_oat_class_offsets_alignment_);
3012 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07003013 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07003014 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07003015 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07003016 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003017 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00003018 DO_STAT(size_type_bss_mappings_);
3019 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07003020 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003021
David Brazdil7b49e6c2016-09-01 11:06:18 +01003022 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
3023
3024 CHECK_EQ(vdex_size_ + oat_size_, size_total);
3025 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07003026 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003027
David Brazdil7b49e6c2016-09-01 11:06:18 +01003028 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
3029 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003030
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003031 write_state_ = WriteState::kWriteHeader;
3032 return true;
3033}
3034
3035bool OatWriter::WriteHeader(OutputStream* out,
3036 uint32_t image_file_location_oat_checksum,
3037 uintptr_t image_file_location_oat_begin,
3038 int32_t image_patch_delta) {
3039 CHECK(write_state_ == WriteState::kWriteHeader);
3040
3041 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
3042 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003043 if (GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003044 CHECK_EQ(image_patch_delta, 0);
3045 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
3046 } else {
3047 CHECK_ALIGNED(image_patch_delta, kPageSize);
3048 oat_header_->SetImagePatchDelta(image_patch_delta);
3049 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003050 oat_header_->UpdateChecksumWithHeaderData();
3051
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003052 const size_t file_offset = oat_data_offset_;
3053
3054 off_t current_offset = out->Seek(0, kSeekCurrent);
3055 if (current_offset == static_cast<off_t>(-1)) {
3056 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
3057 return false;
3058 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003059 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003060 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
3061 return false;
3062 }
David Srbeckybc90fd02015-04-22 19:40:27 +01003063 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003064
3065 // Flush all other data before writing the header.
3066 if (!out->Flush()) {
3067 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
3068 return false;
3069 }
3070 // Write the header.
3071 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00003072 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003073 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
3074 return false;
3075 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003076 // Flush the header data.
3077 if (!out->Flush()) {
3078 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01003079 return false;
3080 }
Vladimir Markof4da6752014-08-01 19:04:18 +01003081
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003082 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
3083 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
3084 return false;
3085 }
3086 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
3087
3088 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003089 return true;
3090}
3091
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003092size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003093 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3094 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003095 // Class offsets are required to be 4 byte aligned.
3096 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
3097 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
3098 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
3099 return 0u;
3100 }
3101 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00003102 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003103 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003104 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003105 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003106 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003107 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003108 }
3109 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003110 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003111}
3112
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003113size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003114 const bool may_have_compiled = MayHaveCompiledMethods();
3115 if (may_have_compiled) {
3116 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
3117 }
3118 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003119 // If there are any classes, the class offsets allocation aligns the offset.
3120 DCHECK_ALIGNED(relative_offset, 4u);
3121 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003122 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003123 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00003124 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003125 relative_offset += oat_class_headers_[i].SizeOf();
3126 if (may_have_compiled) {
3127 if (!oat_classes_[i].Write(this, out)) {
3128 return 0u;
3129 }
3130 relative_offset += oat_classes_[i].SizeOf();
3131 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003132 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003133 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003134}
3135
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003136size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003137 {
3138 size_t vmap_tables_offset = relative_offset;
3139 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
3140 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3141 return 0;
3142 }
3143 relative_offset = visitor.GetOffset();
3144 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003145 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003146 {
3147 size_t method_infos_offset = relative_offset;
3148 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
3149 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3150 return 0;
3151 }
3152 relative_offset = visitor.GetOffset();
3153 size_method_info_ = relative_offset - method_infos_offset;
3154 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003155
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003156 return relative_offset;
3157}
3158
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003159
Vladimir Markof3c52b42017-11-17 17:32:12 +00003160template <typename GetBssOffset>
3161size_t WriteIndexBssMapping(OutputStream* out,
3162 size_t number_of_indexes,
3163 size_t slot_size,
3164 const BitVector& indexes,
3165 GetBssOffset get_bss_offset) {
3166 // Allocate the IndexBssMapping.
3167 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
3168 number_of_indexes, slot_size, indexes, get_bss_offset);
3169 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
3170 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
3171 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
3172 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
3173 mappings->ClearPadding();
3174 // Encode the IndexBssMapping.
3175 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
3176 auto init_it = mappings->begin();
3177 bool first_index = true;
3178 for (uint32_t index : indexes.Indexes()) {
3179 size_t bss_offset = get_bss_offset(index);
3180 if (first_index) {
3181 first_index = false;
3182 encoder.Reset(index, bss_offset);
3183 } else if (!encoder.TryMerge(index, bss_offset)) {
3184 *init_it = encoder.GetEntry();
3185 ++init_it;
3186 encoder.Reset(index, bss_offset);
3187 }
3188 }
3189 // Store the last entry.
3190 *init_it = encoder.GetEntry();
3191 ++init_it;
3192 DCHECK(init_it == mappings->end());
3193
3194 if (!out->WriteFully(storage.get(), mappings_size)) {
3195 return 0u;
3196 }
3197 return mappings_size;
3198}
3199
3200size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
3201 size_t file_offset,
3202 size_t relative_offset) {
3203 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
3204 if (bss_method_entry_references_.empty() &&
3205 bss_type_entry_references_.empty() &&
3206 bss_string_entry_references_.empty()) {
3207 return relative_offset;
3208 }
3209 // If there are any classes, the class offsets allocation aligns the offset
3210 // and we cannot have method bss mappings without class offsets.
3211 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
3212 "IndexBssMapping alignment check.");
3213 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
3214
3215 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003216 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
3217 const DexFile* dex_file = (*dex_files_)[i];
3218 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00003219 auto method_it = bss_method_entry_references_.find(dex_file);
3220 if (method_it != bss_method_entry_references_.end()) {
3221 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003222 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
3223 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00003224 size_t method_mappings_size = WriteIndexBssMapping(
3225 out,
3226 dex_file->NumMethodIds(),
3227 static_cast<size_t>(pointer_size),
3228 method_indexes,
3229 [=](uint32_t index) {
3230 return bss_method_entries_.Get({dex_file, index});
3231 });
3232 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003233 return 0u;
3234 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003235 size_method_bss_mappings_ += method_mappings_size;
3236 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003237 } else {
3238 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3239 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003240
3241 auto type_it = bss_type_entry_references_.find(dex_file);
3242 if (type_it != bss_type_entry_references_.end()) {
3243 const BitVector& type_indexes = type_it->second;
3244 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3245 DCHECK_OFFSET();
3246 size_t type_mappings_size = WriteIndexBssMapping(
3247 out,
3248 dex_file->NumTypeIds(),
3249 sizeof(GcRoot<mirror::Class>),
3250 type_indexes,
3251 [=](uint32_t index) {
3252 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3253 });
3254 if (type_mappings_size == 0u) {
3255 return 0u;
3256 }
3257 size_type_bss_mappings_ += type_mappings_size;
3258 relative_offset += type_mappings_size;
3259 } else {
3260 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3261 }
3262
3263 auto string_it = bss_string_entry_references_.find(dex_file);
3264 if (string_it != bss_string_entry_references_.end()) {
3265 const BitVector& string_indexes = string_it->second;
3266 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3267 DCHECK_OFFSET();
3268 size_t string_mappings_size = WriteIndexBssMapping(
3269 out,
3270 dex_file->NumStringIds(),
3271 sizeof(GcRoot<mirror::String>),
3272 string_indexes,
3273 [=](uint32_t index) {
3274 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3275 });
3276 if (string_mappings_size == 0u) {
3277 return 0u;
3278 }
3279 size_string_bss_mappings_ += string_mappings_size;
3280 relative_offset += string_mappings_size;
3281 } else {
3282 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3283 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003284 }
3285 return relative_offset;
3286}
3287
3288size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3289 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3290
3291 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3292 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3293 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3294 DCHECK_OFFSET();
3295
3296 // Write OatDexFile.
3297 if (!oat_dex_file->Write(this, out)) {
3298 return 0u;
3299 }
3300 relative_offset += oat_dex_file->SizeOf();
3301 }
3302
3303 return relative_offset;
3304}
3305
3306size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003307 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markoa0431112018-06-25 09:32:54 +01003308 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003309
Ian Rogers848871b2013-08-05 10:56:33 -07003310 #define DO_TRAMPOLINE(field) \
3311 do { \
3312 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3313 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003314 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003315 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003316 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003317 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003318 return false; \
3319 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003320 size_ ## field += (field)->size(); \
3321 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003322 DCHECK_OFFSET(); \
3323 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003324
Ian Rogers848871b2013-08-05 10:56:33 -07003325 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003326 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003327 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003328 DO_TRAMPOLINE(quick_resolution_trampoline_);
3329 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3330 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003331 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003332 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003333}
3334
Ian Rogers3d504072014-03-01 09:16:49 -08003335size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003336 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003337 size_t relative_offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003338 if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003339 // As with InitOatCodeDexFiles, also skip the writer if
3340 // compilation was disabled.
3341 if (kOatWriterDebugOatCodeLayout) {
3342 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3343 << this << "), "
3344 << "compilation is disabled";
3345 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003346
Igor Murashkin545412b2017-08-17 15:26:54 -07003347 return relative_offset;
3348 }
3349 ScopedObjectAccess soa(Thread::Current());
3350 DCHECK(ordered_methods_ != nullptr);
3351 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3352 std::move(ordered_methods_);
3353 WriteCodeMethodVisitor visitor(this,
3354 out,
3355 file_offset,
3356 relative_offset,
3357 std::move(*ordered_methods_ptr));
3358 if (UNLIKELY(!visitor.Visit())) {
3359 return 0;
3360 }
3361 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003362
Vladimir Markob163bb72015-03-31 21:49:49 +01003363 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3364 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3365 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3366
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003367 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003368}
3369
Vladimir Markob066d432018-01-03 13:14:37 +00003370size_t OatWriter::WriteDataBimgRelRo(OutputStream* out,
3371 size_t file_offset,
3372 size_t relative_offset) {
3373 if (data_bimg_rel_ro_entries_.empty()) {
3374 return relative_offset;
3375 }
3376
3377 // Write the entire .data.bimg.rel.ro with a single WriteFully().
3378 std::vector<uint32_t> data;
3379 data.reserve(data_bimg_rel_ro_entries_.size());
3380 for (const auto& entry : data_bimg_rel_ro_entries_) {
3381 uint32_t boot_image_offset = entry.first;
3382 data.push_back(boot_image_offset);
3383 }
3384 DCHECK_EQ(data.size(), data_bimg_rel_ro_entries_.size());
3385 DCHECK_OFFSET();
3386 if (!out->WriteFully(data.data(), data.size() * sizeof(data[0]))) {
3387 PLOG(ERROR) << "Failed to write .data.bimg.rel.ro in " << out->GetLocation();
3388 return 0u;
3389 }
3390 DCHECK_EQ(size_data_bimg_rel_ro_, 0u);
3391 size_data_bimg_rel_ro_ = data.size() * sizeof(data[0]);
3392 relative_offset += size_data_bimg_rel_ro_;
3393 return relative_offset;
3394}
3395
Vladimir Marko944da602016-02-19 12:27:55 +00003396bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003397 // Get the elf file offset of the oat file.
3398 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3399 if (raw_file_offset == static_cast<off_t>(-1)) {
3400 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3401 return false;
3402 }
3403 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3404 return true;
3405}
3406
Mathieu Chartier792111c2018-02-15 13:02:15 -08003407bool OatWriter::WriteDexFiles(OutputStream* out,
3408 File* file,
3409 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003410 CopyOption copy_dex_files) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003411 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003412
Mathieu Chartier792111c2018-02-15 13:02:15 -08003413 // If extraction is enabled, only do it if not all the dex files are aligned and uncompressed.
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003414 if (copy_dex_files == CopyOption::kOnlyIfCompressed) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003415 extract_dex_files_into_vdex_ = false;
3416 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3417 if (!oat_dex_file.source_.IsZipEntry()) {
3418 extract_dex_files_into_vdex_ = true;
3419 break;
3420 }
3421 ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
David Sehr79e26072018-04-06 17:58:50 -07003422 if (!entry->IsUncompressed() || !entry->IsAlignedTo(alignof(DexFile::Header))) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003423 extract_dex_files_into_vdex_ = true;
3424 break;
3425 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003426 }
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003427 } else if (copy_dex_files == CopyOption::kAlways) {
3428 extract_dex_files_into_vdex_ = true;
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003429 } else {
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003430 DCHECK(copy_dex_files == CopyOption::kNever);
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003431 extract_dex_files_into_vdex_ = false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003432 }
3433
Mathieu Chartier792111c2018-02-15 13:02:15 -08003434 if (extract_dex_files_into_vdex_) {
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003435 // Add the dex section header.
3436 vdex_size_ += sizeof(VdexFile::DexSectionHeader);
3437 vdex_dex_files_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003438 // Write dex files.
3439 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3440 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
3441 return false;
3442 }
3443 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003444
3445 // Write shared dex file data section and fix up the dex file headers.
3446 vdex_dex_shared_data_offset_ = vdex_size_;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003447 uint32_t shared_data_size = 0u;
3448
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003449 if (dex_container_ != nullptr) {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003450 CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003451 DexContainer::Section* const section = dex_container_->GetDataSection();
3452 if (section->Size() > 0) {
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003453 CHECK(compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003454 const off_t existing_offset = out->Seek(0, kSeekCurrent);
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003455 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3456 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3457 << existing_offset;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003458 return false;
3459 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003460 shared_data_size = section->Size();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003461 if (!out->WriteFully(section->Begin(), shared_data_size)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003462 PLOG(ERROR) << "Failed to write shared data!";
3463 return false;
3464 }
3465 if (!out->Flush()) {
3466 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003467 return false;
3468 }
3469 // Fix up the dex headers to have correct offsets to the data section.
3470 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3471 // Overwrite the header by reading it, updating the offset, and writing it back out.
3472 DexFile::Header header;
3473 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003474 PLOG(ERROR) << "Failed to read dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003475 return false;
3476 }
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003477 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3478 // Non-compact dex file, probably failed to convert due to duplicate methods.
3479 continue;
3480 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003481 CHECK_GT(vdex_dex_shared_data_offset_, oat_dex_file.dex_file_offset_);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003482 // Offset is from the dex file base.
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003483 header.data_off_ = vdex_dex_shared_data_offset_ - oat_dex_file.dex_file_offset_;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003484 // The size should already be what part of the data buffer may be used by the dex.
3485 CHECK_LE(header.data_size_, shared_data_size);
3486 if (!file->PwriteFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003487 PLOG(ERROR) << "Failed to write dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003488 return false;
3489 }
3490 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003491 section->Clear();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003492 }
3493 dex_container_.reset();
Mathieu Chartierf1609832018-01-31 03:09:56 -08003494 } else {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003495 const uint8_t* data_begin = nullptr;
3496 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3497 DexFile::Header header;
3498 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3499 PLOG(ERROR) << "Failed to read dex header";
3500 return false;
3501 }
3502 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3503 // Non compact dex does not have shared data section.
3504 continue;
3505 }
3506 const uint32_t expected_data_off = vdex_dex_shared_data_offset_ -
3507 oat_dex_file.dex_file_offset_;
3508 if (header.data_off_ != expected_data_off) {
3509 PLOG(ERROR) << "Shared data section offset " << header.data_off_
3510 << " does not match expected value " << expected_data_off;
3511 return false;
3512 }
3513 if (oat_dex_file.source_.IsRawData()) {
3514 // Figure out the start of the shared data section so we can copy it below.
3515 const uint8_t* cur_data_begin = oat_dex_file.source_.GetRawData() + header.data_off_;
3516 if (data_begin != nullptr) {
3517 CHECK_EQ(data_begin, cur_data_begin);
Mathieu Chartierf1609832018-01-31 03:09:56 -08003518 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003519 data_begin = cur_data_begin;
3520 }
3521 // The different dex files currently can have different data sizes since
3522 // the dex writer writes them one at a time into the shared section.:w
3523 shared_data_size = std::max(shared_data_size, header.data_size_);
3524 }
3525 // If we are not updating the input vdex, write out the shared data section.
3526 if (!update_input_vdex) {
3527 const off_t existing_offset = out->Seek(0, kSeekCurrent);
3528 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3529 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3530 << existing_offset;
3531 return false;
3532 }
3533 if (!out->WriteFully(data_begin, shared_data_size)) {
3534 PLOG(ERROR) << "Failed to write shared data!";
3535 return false;
3536 }
3537 if (!out->Flush()) {
3538 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
3539 return false;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003540 }
3541 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003542 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003543 vdex_size_ += shared_data_size;
3544 size_dex_file_ += shared_data_size;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003545 } else {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003546 vdex_dex_shared_data_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003547 }
3548
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003549 return true;
3550}
3551
3552void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003553 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3554 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3555 }
3556 zipped_dex_files_.clear();
3557 zip_archives_.clear();
3558 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003559}
3560
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003561bool OatWriter::WriteDexFile(OutputStream* out,
3562 File* file,
3563 OatDexFile* oat_dex_file,
3564 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003565 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003566 return false;
3567 }
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003568 // update_input_vdex disables compact dex and layout.
Mathieu Chartier7c6f6362018-01-14 20:24:38 -08003569 if (profile_compilation_info_ != nullptr ||
3570 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
3571 CHECK(!update_input_vdex)
3572 << "We should never update the input vdex when doing dexlayout or compact dex";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003573 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3574 return false;
3575 }
3576 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003577 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003578 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003579 return false;
3580 }
3581 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003582 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003583 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003584 return false;
3585 }
3586 } else {
3587 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003588 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003589 return false;
3590 }
3591 }
3592
3593 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003594 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3595 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003596 size_dex_file_ += oat_dex_file->dex_file_size_;
3597 return true;
3598}
3599
3600bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3601 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003602 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003603 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray67169412018-01-12 09:06:14 +00003604 size_dex_file_alignment_ += start_offset - initial_offset;
Mathieu Chartier7a26f942018-01-04 18:23:55 -08003605
Mathieu Chartier210531f2018-01-12 10:15:51 -08003606 // Leave extra room for the quicken offset table offset.
3607 start_offset += sizeof(VdexFile::QuickeningTableOffsetType);
3608 // TODO: Not count the offset as part of alignment.
3609 size_dex_file_alignment_ += sizeof(VdexFile::QuickeningTableOffsetType);
3610
3611 size_t file_offset = start_offset;
3612
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003613 // Seek to the start of the dex file and flush any pending operations in the stream.
3614 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003615 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3616 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003617 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003618 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003619 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3620 return false;
3621 }
3622 if (!out->Flush()) {
3623 PLOG(ERROR) << "Failed to flush before writing dex file."
3624 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3625 return false;
3626 }
3627 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003628 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003629 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003630 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003631 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3632 return false;
3633 }
3634
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003635 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003636 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003637 return true;
3638}
3639
Jeff Hao608f2ce2016-10-19 11:17:11 -07003640bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
David Brazdil2b9c35b2018-01-12 15:44:43 +00003641 // Open dex files and write them into `out`.
3642 // Note that we only verify dex files which do not belong to the boot class path.
3643 // This is because those have been processed by `hiddenapi` and would not pass
3644 // some of the checks. No guarantees are lost, however, as `hiddenapi` verifies
3645 // the dex files prior to processing.
Jeff Hao608f2ce2016-10-19 11:17:11 -07003646 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3647 std::string error_msg;
3648 std::string location(oat_dex_file->GetLocation());
3649 std::unique_ptr<const DexFile> dex_file;
David Sehr013fd802018-01-11 22:55:24 -08003650 const ArtDexFileLoader dex_file_loader;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003651 if (oat_dex_file->source_.IsZipEntry()) {
3652 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
Andreas Gampefb008f42018-04-23 10:01:16 -07003653 std::unique_ptr<MemMap> mem_map;
3654 {
3655 TimingLogger::ScopedTiming extract("Unzip", timings_);
3656 mem_map.reset(zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
3657 }
Jeff Hao41b2f532017-03-02 16:36:31 -08003658 if (mem_map == nullptr) {
3659 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3660 return false;
3661 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003662 TimingLogger::ScopedTiming extract("Open", timings_);
David Sehr013fd802018-01-11 22:55:24 -08003663 dex_file = dex_file_loader.Open(location,
Andreas Gampefb008f42018-04-23 10:01:16 -07003664 zip_entry->GetCrc32(),
3665 std::move(mem_map),
Vladimir Markoa0431112018-06-25 09:32:54 +01003666 /* verify */ !GetCompilerOptions().IsBootImage(),
Andreas Gampefb008f42018-04-23 10:01:16 -07003667 /* verify_checksum */ true,
3668 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003669 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003670 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003671 int dup_fd = dup(raw_file->Fd());
3672 if (dup_fd < 0) {
3673 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3674 return false;
3675 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003676 TimingLogger::ScopedTiming extract("Open", timings_);
David Brazdil2b9c35b2018-01-12 15:44:43 +00003677 dex_file = dex_file_loader.OpenDex(dup_fd, location,
Vladimir Markoa0431112018-06-25 09:32:54 +01003678 /* verify */ !GetCompilerOptions().IsBootImage(),
David Brazdil2b9c35b2018-01-12 15:44:43 +00003679 /* verify_checksum */ true,
3680 /* mmap_shared */ false,
3681 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003682 } else {
3683 // The source data is a vdex file.
3684 CHECK(oat_dex_file->source_.IsRawData())
3685 << static_cast<size_t>(oat_dex_file->source_.GetType());
3686 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3687 // Note: The raw data has already been checked to contain the header
3688 // and all the data that the header specifies as the file size.
3689 DCHECK(raw_dex_file != nullptr);
3690 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3691 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3692 // Since the source may have had its layout changed, or may be quickened, don't verify it.
David Sehr013fd802018-01-11 22:55:24 -08003693 dex_file = dex_file_loader.Open(raw_dex_file,
3694 header->file_size_,
3695 location,
3696 oat_dex_file->dex_file_location_checksum_,
3697 nullptr,
3698 /* verify */ false,
3699 /* verify_checksum */ false,
3700 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003701 }
Jeff Haode197542017-02-03 10:48:13 -08003702 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003703 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003704 return false;
3705 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003706 Options options;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003707 options.compact_dex_level_ = compact_dex_level_;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003708 options.update_checksum_ = true;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -08003709 DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003710 const uint8_t* dex_src = nullptr;
Andreas Gampefb008f42018-04-23 10:01:16 -07003711 {
3712 TimingLogger::ScopedTiming extract("ProcessDexFile", timings_);
3713 if (dex_layout.ProcessDexFile(location.c_str(),
3714 dex_file.get(),
3715 0,
3716 &dex_container_,
3717 &error_msg)) {
3718 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3719 // Dex layout can affect the size of the dex file, so we update here what we have set
3720 // when adding the dex file as a source.
3721 const UnalignedDexFileHeader* header =
3722 AsUnalignedDexFileHeader(dex_container_->GetMainSection()->Begin());
3723 oat_dex_file->dex_file_size_ = header->file_size_;
3724 dex_src = dex_container_->GetMainSection()->Begin();
3725 } else {
3726 LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
3727 // Since we failed to convert the dex, just copy the input dex.
3728 dex_src = dex_file->Begin();
3729 }
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003730 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003731 {
3732 TimingLogger::ScopedTiming extract("WriteDexFile", timings_);
3733 if (!WriteDexFile(out, oat_dex_file, dex_src, /* update_input_vdex */ false)) {
3734 return false;
3735 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003736 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003737 if (dex_container_ != nullptr) {
3738 // Clear the main section in case we write more data into the container.
3739 dex_container_->GetMainSection()->Clear();
3740 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003741 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003742 return true;
3743}
3744
David Brazdil7b49e6c2016-09-01 11:06:18 +01003745bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003746 File* file,
3747 OatDexFile* oat_dex_file,
3748 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003749 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003750 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003751
3752 // Extract the dex file and get the extracted size.
3753 std::string error_msg;
3754 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3755 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3756 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3757 return false;
3758 }
3759 if (file->Flush() != 0) {
3760 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3761 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3762 return false;
3763 }
3764 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3765 if (extracted_end == static_cast<off_t>(-1)) {
3766 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3767 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3768 return false;
3769 }
3770 if (extracted_end < static_cast<off_t>(start_offset)) {
3771 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3772 << " Start: " << start_offset
3773 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3774 return false;
3775 }
3776 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3777 if (extracted_size < sizeof(DexFile::Header)) {
3778 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3779 << extracted_size << " File: " << oat_dex_file->GetLocation();
3780 return false;
3781 }
3782
3783 // Read the dex file header and extract required data to OatDexFile.
3784 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3785 if (actual_offset != static_cast<off_t>(start_offset)) {
3786 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3787 << " Expected: " << start_offset
3788 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3789 return false;
3790 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003791 if (extracted_size < oat_dex_file->dex_file_size_) {
3792 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3793 << " file size from header: " << oat_dex_file->dex_file_size_
3794 << " File: " << oat_dex_file->GetLocation();
3795 return false;
3796 }
3797
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003798 // Seek both file and stream to the end offset.
3799 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3800 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3801 if (actual_offset != static_cast<off_t>(end_offset)) {
3802 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3803 << " Expected: " << end_offset
3804 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3805 return false;
3806 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003807 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003808 if (actual_offset != static_cast<off_t>(end_offset)) {
3809 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3810 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3811 return false;
3812 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003813 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003814 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3815 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3816 return false;
3817 }
3818
3819 // If we extracted more than the size specified in the header, truncate the file.
3820 if (extracted_size > oat_dex_file->dex_file_size_) {
3821 if (file->SetLength(end_offset) != 0) {
3822 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003823 << " File: " << oat_dex_file->GetLocation()
3824 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003825 return false;
3826 }
3827 }
3828
3829 return true;
3830}
3831
David Brazdil7b49e6c2016-09-01 11:06:18 +01003832bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003833 File* file,
3834 OatDexFile* oat_dex_file,
3835 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003836 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003837 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003838
3839 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3840 if (input_offset != static_cast<off_t>(0)) {
3841 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3842 << " Expected: 0"
3843 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3844 return false;
3845 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003846
3847 // Copy the input dex file using sendfile().
3848 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3849 PLOG(ERROR) << "Failed to copy dex file to oat file."
3850 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3851 return false;
3852 }
3853 if (file->Flush() != 0) {
3854 PLOG(ERROR) << "Failed to flush dex file."
3855 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3856 return false;
3857 }
3858
3859 // Check file position and seek the stream to the end offset.
3860 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3861 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3862 if (actual_offset != static_cast<off_t>(end_offset)) {
3863 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3864 << " Expected: " << end_offset
3865 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3866 return false;
3867 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003868 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003869 if (actual_offset != static_cast<off_t>(end_offset)) {
3870 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3871 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3872 return false;
3873 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003874 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003875 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3876 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3877 return false;
3878 }
3879
3880 return true;
3881}
3882
David Brazdil7b49e6c2016-09-01 11:06:18 +01003883bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003884 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003885 const uint8_t* dex_file,
3886 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003887 // Note: The raw data has already been checked to contain the header
3888 // and all the data that the header specifies as the file size.
3889 DCHECK(dex_file != nullptr);
3890 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3891 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3892
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003893 if (update_input_vdex) {
3894 // The vdex already contains the dex code, no need to write it again.
3895 } else {
3896 if (!out->WriteFully(dex_file, header->file_size_)) {
3897 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3898 << " to " << out->GetLocation();
3899 return false;
3900 }
3901 if (!out->Flush()) {
3902 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3903 << " File: " << oat_dex_file->GetLocation();
3904 return false;
3905 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003906 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003907 return true;
3908}
3909
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003910bool OatWriter::OpenDexFiles(
3911 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003912 bool verify,
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003913 /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003914 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3915 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3916
3917 if (oat_dex_files_.empty()) {
3918 // Nothing to do.
3919 return true;
3920 }
3921
Mathieu Chartier792111c2018-02-15 13:02:15 -08003922 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003923 std::vector<std::unique_ptr<const DexFile>> dex_files;
3924 std::vector<std::unique_ptr<MemMap>> maps;
3925 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3926 std::string error_msg;
Mathieu Chartier792111c2018-02-15 13:02:15 -08003927 MemMap* map = oat_dex_file.source_.GetZipEntry()->MapDirectlyOrExtract(
3928 oat_dex_file.dex_file_location_data_, "zipped dex", &error_msg);
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003929 if (map == nullptr) {
3930 LOG(ERROR) << error_msg;
3931 return false;
3932 }
3933 maps.emplace_back(map);
3934 // Now, open the dex file.
3935 const ArtDexFileLoader dex_file_loader;
3936 dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
3937 map->Size(),
3938 oat_dex_file.GetLocation(),
3939 oat_dex_file.dex_file_location_checksum_,
3940 /* oat_dex_file */ nullptr,
3941 verify,
3942 verify,
3943 &error_msg));
3944 if (dex_files.back() == nullptr) {
3945 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3946 << " Error: " << error_msg;
3947 return false;
3948 }
3949 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3950 }
3951 *opened_dex_files_map = std::move(maps);
3952 *opened_dex_files = std::move(dex_files);
3953 CloseSources();
3954 return true;
3955 }
3956 // We could have closed the sources at the point of writing the dex files, but to
3957 // make it consistent with the case we're not writing the dex files, we close them now.
3958 CloseSources();
3959
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003960 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003961 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003962
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003963 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003964 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3965 length,
3966 PROT_READ | PROT_WRITE,
3967 MAP_SHARED,
3968 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003969 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003970 /* low_4gb */ false,
3971 file->GetPath().c_str(),
3972 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003973 if (dex_files_map == nullptr) {
3974 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3975 << " error: " << error_msg;
3976 return false;
3977 }
David Sehr013fd802018-01-11 22:55:24 -08003978 const ArtDexFileLoader dex_file_loader;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003979 std::vector<std::unique_ptr<const DexFile>> dex_files;
3980 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003981 const uint8_t* raw_dex_file =
3982 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003983
3984 if (kIsDebugBuild) {
3985 // Sanity check our input files.
3986 // Note that ValidateDexFileHeader() logs error messages.
3987 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3988 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003989 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3990 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003991
3992 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3993 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3994 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003995 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3996 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003997 }
3998
3999 // Now, open the dex file.
David Sehr013fd802018-01-11 22:55:24 -08004000 dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
4001 oat_dex_file.dex_file_size_,
4002 oat_dex_file.GetLocation(),
4003 oat_dex_file.dex_file_location_checksum_,
4004 /* oat_dex_file */ nullptr,
4005 verify,
4006 verify,
4007 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004008 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08004009 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
4010 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004011 return false;
4012 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004013
4014 // Set the class_offsets size now that we have easy access to the DexFile and
David Sehr013fd802018-01-11 22:55:24 -08004015 // it has been verified in dex_file_loader.Open.
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004016 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004017 }
4018
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00004019 opened_dex_files_map->push_back(std::move(dex_files_map));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004020 *opened_dex_files = std::move(dex_files);
4021 return true;
4022}
4023
4024bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01004025 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004026 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
4027 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
4028
David Brazdil7b49e6c2016-09-01 11:06:18 +01004029 uint32_t expected_offset = oat_data_offset_ + oat_size_;
4030 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
4031 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
4032 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
4033 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
4034 return false;
4035 }
4036
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004037 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
4038 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
4039 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00004040 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
4041
4042 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
4043 oat_dex_file->class_offsets_.empty()) {
4044 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004045 }
David Brazdil181e1cc2016-09-01 16:38:47 +00004046
4047 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
4048 if (table_size == 0u) {
4049 continue;
4050 }
4051
4052 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07004053 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004054 const DexFile& dex_file = *opened_dex_files[i];
4055 {
Vladimir Markoea341d22018-05-11 10:33:37 +01004056 TypeLookupTable type_lookup_table = TypeLookupTable::Create(dex_file);
Mathieu Chartier1b868492016-11-16 16:22:37 -08004057 type_lookup_table_oat_dex_files_.push_back(
4058 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
4059 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
4060 }
Vladimir Markoea341d22018-05-11 10:33:37 +01004061 const TypeLookupTable& table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
4062 DCHECK(table.Valid());
David Brazdil181e1cc2016-09-01 16:38:47 +00004063
4064 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01004065 size_t initial_offset = oat_size_;
4066 size_t rodata_offset = RoundUp(initial_offset, 4);
4067 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00004068
4069 if (padding_size != 0u) {
4070 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01004071 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00004072 PLOG(ERROR) << "Failed to write lookup table alignment padding."
4073 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01004074 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00004075 return false;
4076 }
4077 }
4078
4079 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01004080 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
Vladimir Markoea341d22018-05-11 10:33:37 +01004081 DCHECK_EQ(table_size, table.RawDataLength());
David Brazdil181e1cc2016-09-01 16:38:47 +00004082
Vladimir Markoea341d22018-05-11 10:33:37 +01004083 if (!oat_rodata->WriteFully(table.RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00004084 PLOG(ERROR) << "Failed to write lookup table."
4085 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01004086 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00004087 return false;
4088 }
4089
4090 oat_dex_file->lookup_table_offset_ = rodata_offset;
4091
David Brazdil7b49e6c2016-09-01 11:06:18 +01004092 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00004093 size_oat_lookup_table_ += table_size;
4094 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004095 }
4096
David Brazdil7b49e6c2016-09-01 11:06:18 +01004097 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00004098 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01004099 << " File: " << oat_rodata->GetLocation();
4100 return false;
4101 }
4102
4103 return true;
4104}
4105
Mathieu Chartier120aa282017-08-05 16:03:03 -07004106bool OatWriter::WriteDexLayoutSections(
4107 OutputStream* oat_rodata,
4108 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
4109 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
4110
4111 if (!kWriteDexLayoutInfo) {
4112 return true;;
4113 }
4114
4115 uint32_t expected_offset = oat_data_offset_ + oat_size_;
4116 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
4117 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
4118 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
4119 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
4120 return false;
4121 }
4122
4123 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
4124 size_t rodata_offset = oat_size_;
4125 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
4126 OatDexFile* oat_dex_file = &oat_dex_files_[i];
4127 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
4128
4129 // Write dex layout section alignment bytes.
4130 const size_t padding_size =
4131 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
4132 if (padding_size != 0u) {
4133 std::vector<uint8_t> buffer(padding_size, 0u);
4134 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
4135 PLOG(ERROR) << "Failed to write lookup table alignment padding."
4136 << " File: " << oat_dex_file->GetLocation()
4137 << " Output: " << oat_rodata->GetLocation();
4138 return false;
4139 }
4140 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
4141 rodata_offset += padding_size;
4142 }
4143
4144 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
4145 DCHECK_EQ(oat_data_offset_ + rodata_offset,
4146 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
4147 DCHECK(oat_dex_file != nullptr);
4148 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
4149 sizeof(oat_dex_file->dex_sections_layout_))) {
4150 PLOG(ERROR) << "Failed to write dex layout sections."
4151 << " File: " << oat_dex_file->GetLocation()
4152 << " Output: " << oat_rodata->GetLocation();
4153 return false;
4154 }
4155 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
4156 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
4157 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
4158 }
4159 oat_size_ = rodata_offset;
4160
4161 if (!oat_rodata->Flush()) {
4162 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
4163 << " File: " << oat_rodata->GetLocation();
4164 return false;
4165 }
4166
4167 return true;
4168}
4169
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004170bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004171 // Write checksums
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004172 off_t checksums_offset = sizeof(VdexFile::VerifierDepsHeader);
4173 off_t actual_offset = vdex_out->Seek(checksums_offset, kSeekSet);
4174 if (actual_offset != checksums_offset) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004175 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
4176 << " File: " << vdex_out->GetLocation();
4177 return false;
4178 }
4179
4180 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
4181 OatDexFile* oat_dex_file = &oat_dex_files_[i];
4182 if (!vdex_out->WriteFully(
4183 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
4184 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
4185 << vdex_out->GetLocation();
4186 return false;
4187 }
4188 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
4189 }
4190
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004191 // Maybe write dex section header.
4192 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
4193 DCHECK_NE(vdex_quickening_info_offset_, 0u);
4194
4195 bool has_dex_section = extract_dex_files_into_vdex_;
4196 if (has_dex_section) {
4197 DCHECK_NE(vdex_dex_files_offset_, 0u);
4198 size_t dex_section_size = vdex_dex_shared_data_offset_ - vdex_dex_files_offset_;
4199 size_t dex_shared_data_size = vdex_verifier_deps_offset_ - vdex_dex_shared_data_offset_;
4200 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
4201
4202 VdexFile::DexSectionHeader dex_section_header(dex_section_size,
4203 dex_shared_data_size,
4204 quickening_info_section_size);
4205 if (!vdex_out->WriteFully(&dex_section_header, sizeof(VdexFile::DexSectionHeader))) {
4206 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
4207 return false;
4208 }
4209 size_vdex_header_ += sizeof(VdexFile::DexSectionHeader);
4210 }
4211
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00004212 // Write header.
4213 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01004214 if (actual_offset != 0) {
4215 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
4216 << " File: " << vdex_out->GetLocation();
4217 return false;
4218 }
4219
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01004220 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01004221
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004222 VdexFile::VerifierDepsHeader deps_header(
4223 oat_dex_files_.size(), verifier_deps_section_size, has_dex_section);
4224 if (!vdex_out->WriteFully(&deps_header, sizeof(VdexFile::VerifierDepsHeader))) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01004225 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004226 return false;
4227 }
Nicolas Geoffray3a293552018-03-02 10:52:16 +00004228 size_vdex_header_ += sizeof(VdexFile::VerifierDepsHeader);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004229
David Brazdil5d5a36b2016-09-14 15:34:10 +01004230 if (!vdex_out->Flush()) {
4231 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
4232 << " File: " << vdex_out->GetLocation();
4233 return false;
4234 }
4235
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004236 return true;
4237}
4238
Vladimir Markof4da6752014-08-01 19:04:18 +01004239bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004240 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
4241}
4242
4243bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004244 static const uint8_t kPadding[] = {
4245 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
4246 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004247 DCHECK_LE(size, sizeof(kPadding));
4248 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004249 return false;
4250 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004251 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01004252 return true;
4253}
4254
Vladimir Marko944da602016-02-19 12:27:55 +00004255void OatWriter::SetMultiOatRelativePatcherAdjustment() {
4256 DCHECK(dex_files_ != nullptr);
4257 DCHECK(relative_patcher_ != nullptr);
4258 DCHECK_NE(oat_data_offset_, 0u);
4259 if (image_writer_ != nullptr && !dex_files_->empty()) {
4260 // The oat data begin may not be initialized yet but the oat file offset is ready.
4261 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
4262 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
4263 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01004264 }
4265}
4266
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004267OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
4268 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004269 CreateTypeLookupTable create_type_lookup_table,
4270 uint32_t dex_file_location_checksum,
4271 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004272 : source_(source),
4273 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004274 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004275 offset_(0),
4276 dex_file_location_size_(strlen(dex_file_location)),
4277 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004278 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004279 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004280 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004281 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00004282 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00004283 type_bss_mapping_offset_(0u),
4284 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004285 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004286 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07004287}
4288
4289size_t OatWriter::OatDexFile::SizeOf() const {
4290 return sizeof(dex_file_location_size_)
4291 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08004292 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08004293 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004294 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004295 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004296 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00004297 + sizeof(type_bss_mapping_offset_)
4298 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004299 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004300}
4301
4302bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
4303 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08004304 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004305
Vladimir Markoe079e212016-05-25 12:49:49 +01004306 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004307 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004308 return false;
4309 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004310 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004311
Vladimir Markoe079e212016-05-25 12:49:49 +01004312 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004313 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004314 return false;
4315 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004316 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004317
Vladimir Markoe079e212016-05-25 12:49:49 +01004318 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004319 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004320 return false;
4321 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004322 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004323
Vladimir Markoe079e212016-05-25 12:49:49 +01004324 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004325 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08004326 return false;
4327 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004328 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004329
Vladimir Markoe079e212016-05-25 12:49:49 +01004330 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004331 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
4332 return false;
4333 }
4334 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
4335
Vladimir Markoe079e212016-05-25 12:49:49 +01004336 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03004337 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
4338 return false;
4339 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004340 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004341
Mathieu Chartier120aa282017-08-05 16:03:03 -07004342 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4343 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4344 return false;
4345 }
4346 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4347
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004348 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4349 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4350 return false;
4351 }
4352 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4353
Vladimir Markof3c52b42017-11-17 17:32:12 +00004354 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4355 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4356 return false;
4357 }
4358 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4359
4360 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4361 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4362 return false;
4363 }
4364 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4365
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004366 return true;
4367}
4368
4369bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004370 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004371 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4372 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004373 return false;
4374 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004375 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004376 return true;
4377}
4378
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004379OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004380 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004381 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004382 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004383 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004384 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004385
Brian Carlstromba150c32013-08-27 17:31:03 -07004386 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4387
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004388 method_offsets_.resize(compiled_methods_with_code);
4389 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004390
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004391 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4392 // We only create this instance if there are at least some compiled.
4393 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004394 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004395 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4396 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4397 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4398 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004399 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004400 method_bitmap_size_ = 0;
4401 }
4402
4403 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004404 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004405 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004406 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4407 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004408 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004409 method_bitmap_->SetBit(i);
4410 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004411 } else {
4412 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004413 }
4414 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004415}
4416
Brian Carlstrom265091e2013-01-30 14:08:26 -08004417size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004418 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004419 + method_bitmap_size_
4420 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004421}
4422
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004423bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4424 OutputStream* out,
4425 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004426 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004427 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004428 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004429 return false;
4430 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004431 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004432
Vladimir Markoe079e212016-05-25 12:49:49 +01004433 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004434 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004435 return false;
4436 }
4437 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004438 return true;
4439}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004440
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004441bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004442 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004443 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004444 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004445 return false;
4446 }
4447 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004448
Vladimir Markoe079e212016-05-25 12:49:49 +01004449 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004450 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004451 return false;
4452 }
4453 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4454 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004455
Vladimir Markoe079e212016-05-25 12:49:49 +01004456 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004457 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004458 return false;
4459 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004460 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004461 return true;
4462}
4463
David Srbecky32210b92017-12-04 14:39:21 +00004464debug::DebugInfo OatWriter::GetDebugInfo() const {
4465 debug::DebugInfo debug_info{};
4466 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
David Srbecky96c84462018-02-05 15:42:40 +00004467 if (VdexWillContainDexFiles()) {
David Srbecky25931622018-01-18 22:55:20 +00004468 DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
4469 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
4470 const DexFile* dex_file = (*dex_files_)[i];
4471 const OatDexFile& oat_dex_file = oat_dex_files_[i];
David Srbecky96c84462018-02-05 15:42:40 +00004472 uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
4473 if (dex_file_offset != 0) {
4474 debug_info.dex_files.emplace(dex_file_offset, dex_file);
4475 }
David Srbecky32210b92017-12-04 14:39:21 +00004476 }
4477 }
4478 return debug_info;
4479}
4480
Vladimir Marko74527972016-11-29 15:57:32 +00004481} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004482} // namespace art